如何防止创建空文件

本文关键字:文件 创建 何防止 | 更新日期: 2023-09-27 18:17:58

我有一个基于Repeater控件中的项创建的文件,如果每个项的radioButton为"Yes"。我的问题是,如果文件是空的,它仍在创建中。我试过FileName。长度> 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.
    }
}

这个怎么样:

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来确保释放资源的代码总是被击中。

您应该将其更改为仅在需要写入数据时才写入和创建文件。

一种简单的方法是将所有内容存储在内存中,例如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));
}

您可以在打开流写入器之前检查是否有任何项目符合保存条件,如下所示:

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