如何防止创建空文件

时间:2015-10-16 15:19:59

标签: c#

如果每个项目的radioButton为“是”,我有一个基于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);
    }
}

5 个答案:

答案 0 :(得分:2)

听起来你想要检测文件是否为空。使用:

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

FileName.Length只是告诉你文件名有多长 - 不是usefule

答案 1 :(得分:0)

为什么不先检查文件是否存在?这应该可以解决您的异常问题!如果您想知道文件是否为空,我建议您检查您要写入文件的内容,并确保它不是全部为空,如果您确实有内容,那么写入该文件?

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

答案 2 :(得分:0)

如果要写入一些数据,则应将其更改为仅写入和创建文件。

执行此操作的一种简单方法是使用类似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));
}

答案 3 :(得分:0)

这个怎么样:

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确保您的资源永久命中。

答案 4 :(得分:0)

您可以在打开流式编写器之前检​​查是否有任何项目符合保存条件:

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(...)在此处不起作用,因为它不会在驱动器号后面添加路径分隔符。