簡體   English   中英

如何防止創建空文件

[英]How to prevent empty file from being created

如果每個項目的單選按鈕為“是”,則我有一個基於Repeater控件中的項目創建的文件。 我的問題是,如果文件為空,則仍在創建它。 我已經嘗試過FileName.Length> 0和其他可能的解決方案,但是卻收到無法找到該文件的錯誤。 我確定問題在我的邏輯范圍內,但我看不到哪里。 有任何想法嗎?

protected void btnContinue_Click(object sender, EventArgs e)
{
    string JobName;
    string FileName;

    StreamWriter sw;
    string Name, Company, Date;

    JobName = TYest + "_" + System.DateTime.Now;
    JobName = JobName.Replace(":", "").Replace("/", "").Replace(" ", "");
    FileName = JobName + ".txt";

    sw = new StreamWriter(C: +"/" + FileName, false, Encoding.GetEncoding(1250));

    foreach ( RepeaterItem rpItems in rpGetData.Items )
    {
        RadioButtonList rbYesNo = (RadioButtonList)rpItems.FindControl("rbBadge");

        if ( rbYesNo.SelectedItem.Text == "Yes" )
        {
            Label rName = (Label)rpItems.FindControl("lblName");
            Label rCompany = (Label)rpItems.FindControl("lblCompany");
            Label rFacilityName = (Label)rpItems.FindControl("lblFacility_Hidden");
            Name = rName.Text;
            Company = rCompany.Text;
            Date = System.DateTime.Now.ToString("MM/dd/yyyy");

            sw.WriteLine("Name," + Name);
            sw.WriteLine("Company," + Company);
            sw.WriteLine("Date," + Date);
            sw.WriteLine("*PRINTLABEL");
        }

        sw.Flush();
        sw.Dispose();

        if ( File.Exists("C:/" + FileName) )
        {
            try
            {
                File.Copy(+"C:/" + FileName, LoftwareDropPath + FileName, true);
            }
            catch ( Exception ex )
            {
                string msgE = "Error";
                msgE += ex.Message;
                throw new Exception(msgE);
            }
        }
        else
        {
            //Do something if temp file not created properly
            lblMessage.Text = "An error has occurred. Plese see your host to get a printed name badge.";
        }

        MessageBox messageBox = new MessageBox();
        messageBox.MessageTitle = "Printed?";
        messageBox.MessageText = "If not, please see host.";
        Literal1.Text = messageBox.Show(this);
    }
}

聽起來好像您想檢測文件是否為空。 采用:

long length = new System.IO.FileInfo(path).Length;
if(length == 0)....

FileName.Length只是告訴您文件名有多長-沒用

為什么不先檢查文件是否存在? 那應該解決您的異常問題! 如果您想知道文件是否為空,建議您檢查要寫入的文件,並確保文件不全為空,然后在實際有內容的情況下寫入文件?

if(File.Exists(File))
{
    if(new FileInfo(File).Length > 0)
    {
         //Do Stuff.
    }
}

您應該將其更改為僅在有一些數據要寫入時才寫入並創建文件。

一種簡單的方法是使用StringBuilder類的東西來存儲所有內存,然后如果有要寫入的內容,則將字符串生成器的內容寫入文件中:

var sb = new StringBuilder();

foreach (RepeaterItem rpItems in rpGetData.Items)
{
    RadioButtonList rbYesNo = (RadioButtonList)rpItems.FindControl("rbBadge");

    if (rbYesNo.SelectedItem.Text == "Yes")
    {
        // ..omitted..

        sb.AppendLine("Name," + Name);
        sb.AppendLine("Company," + Company);
        sb.AppendLine("Date," + Date);
        sb.AppendLine("*PRINTLABEL");
    }
}

if (sb.Length > 0)
{
    File.WriteAllText(FileName, sb.ToString(), Encoding.GetEncoding(1250));
}

這個怎么樣:

StreamWriter sw = null;
string Name, Company,  Date;   

JobName = TYest + "_" + System.DateTime.Now;
JobName = JobName.Replace(":", "").Replace("/", "").Replace(" ", "");
FileName = @"C:\" + JobName + ".txt";
try
{
 foreach (RepeaterItem rpItems in rpGetData.Items)
 {

     RadioButtonList rbYesNo = (RadioButtonList)rpItems.FindControl("rbBadge");

      if (rbYesNo.SelectedItem.Text == "Yes")
       {
           if (null == sw)
               sw = new StreamWriter(FileName, false, Encoding.GetEncoding(1250));
           Label rName = (Label)rpItems.FindControl("lblName");
           Label rCompany = (Label)rpItems.FindControl("lblCompany");
           Label rFacilityName = (Label)rpItems.FindControl("lblFacility_Hidden");
           Name = rName.Text;
           Company = rCompany.Text;
           Date = System.DateTime.Now.ToString("MM/dd/yyyy");

           sw.WriteLine("Name," + Name);
           sw.WriteLine("Company," + Company);
           sw.WriteLine("Date," + Date);
           sw.WriteLine("*PRINTLABEL");
  }
}
finally
{
    if (null != sw)
    {
        sw.Flush();
        sw.Dispose();
    }
}

一次完全構建您的FileName,這樣您就知道它總是相同的。 然后,僅在要編寫某些內容時才創建StreamWriter。 另外,請使用try..finally以確保始終能找到釋放您的資源的代碼。

您可以在打開流編寫器之前檢​​查是否有任何項目可以保存,如下所示:

var itemsToBeSaved = rpGetData.Items
    Where(ri => ((RadioButtonList)ri.FindControl("rbBadge")).SelectedItem.Text == "Yes");

if (itemsToBeSaved.Any()) {
    string path = @"C:\" + FileName;
    using (var sw = new StreamWriter(path, false, Encoding.GetEncoding(1250))) {
        foreach (RepeaterItem rpItems in itemsToBeSaved) {
            Label rName = (Label)rpItems.FindControl("lblName");
            Label rCompany = (Label)rpItems.FindControl("lblCompany");
            Label rFacilityName = (Label)rpItems.FindControl("lblFacility_Hidden");
            Name = rName.Text;
            Company = rCompany.Text;
            Date = System.DateTime.Now.ToString("MM/dd/yyyy");

            sw.WriteLine("Name," + Name);
            sw.WriteLine("Company," + Company);
            sw.WriteLine("Date," + Date);
            sw.WriteLine("*PRINTLABEL");
        }
    } // Flushes, Closes und Disposes the stream automatically.
}

第一條語句准備僅包含要保存的重復項的過濾枚舉。 itemsToBeSaved.Any()測試此枚舉是否包含至少一項。 然后,此枚舉將在foreach語句中重用。 因此,沒有必要再次檢查條件。

using語句負責在所有情況下關閉流,即使在寫入文件時發生異常也是如此。 我還在using語句中聲明了流編寫器。 因此,您可以刪除聲明StreamWriter sw = null;

還請注意表達式@"C:\\" + FileName @使字符串常量成為逐字字符串。 這意味着通常的轉義字符'\\'失去了意義並按原樣使用。 Path.Combine(...)在這里不起作用,因為它沒有在驅動器號后添加路徑分隔符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM