简体   繁体   English

如何防止创建空文件

[英]How to prevent empty file from being created

I have a file that is being created based on the items in a Repeater control if the radioButton for each item is "Yes". 如果每个项目的单选按钮为“是”,则我有一个基于Repeater控件中的项目创建的文件。 My issue that if the file is empty, it is still being created. 我的问题是,如果文件为空,则仍在创建它。 I have tried FileName.Length > 0 and other possible solutions but I get errors that the file can not be found. 我已经尝试过FileName.Length> 0和其他可能的解决方案,但是却收到无法找到该文件的错误。 I am sure the issue is within my logic but I cant see where. 我确定问题在我的逻辑范围内,但我看不到哪里。 Any ideas? 有任何想法吗?

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);
    }
}

sounds like you want to detect if a file is empty. 听起来好像您想检测文件是否为空。 Use: 采用:

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

FileName.Length just tells you how long the file name is - not usefule FileName.Length只是告诉您文件名有多长-没用

Why not check if the file exists first? 为什么不先检查文件是否存在? That should solve your exception problems! 那应该解决您的异常问题! If you want to know if the file is empty I would recommend checking what you're writing to the file and making sure it's not all empty and THEN write to the file if you actually have content? 如果您想知道文件是否为空,建议您检查要写入的文件,并确保文件不全为空,然后在实际有内容的情况下写入文件?

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

You should change it to only write and create the file when you have some data to write. 您应该将其更改为仅在有一些数据要写入时才写入并创建文件。

A simple way of doing this is to store everything memory with something like a StringBuilder , then afterwards write the contents of the string builder to the file if there is something to write: 一种简单的方法是使用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));
}

How about this: 这个怎么样:

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();
    }
}

Build your FileName completely once so that you know it is always the same. 一次完全构建您的FileName,这样您就知道它总是相同的。 Then only create your StreamWriter if something is going to be written. 然后,仅在要编写某些内容时才创建StreamWriter。 Also, use a try..finally to make sure your code to free your resources is always hit. 另外,请使用try..finally以确保始终能找到释放您的资源的代码。

You can check whether any items are eligible for saving before opening the stream writer like this: 您可以在打开流编写器之前检​​查是否有任何项目可以保存,如下所示:

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.
}

The first statement prepares a filtered enumeration of repeater items containing only the ones to be saved. 第一条语句准备仅包含要保存的重复项的过滤枚举。 itemsToBeSaved.Any() tests if this enumeration contains at least one item. itemsToBeSaved.Any()测试此枚举是否包含至少一项。 This enumeration is then reused in the foreach statement. 然后,此枚举将在foreach语句中重用。 Therefore it is not necessary to check the conditions again. 因此,没有必要再次检查条件。

The using statement takes care of closing the stream in all situations, even if an exception should occur while writing to the file. using语句负责在所有情况下关闭流,即使在写入文件时发生异常也是如此。 I also declared the stream writer in the using statement. 我还在using语句中声明了流编写器。 Therefore you can delete your declaration StreamWriter sw = null; 因此,您可以删除声明StreamWriter sw = null; .

Also note the expression @"C:\\" + FileName . 还请注意表达式@"C:\\" + FileName The @ makes the string constant a verbatim string. @使字符串常量成为逐字字符串。 This means that the usual escape character '\\' loses its meaning and is used as is . 这意味着通常的转义字符'\\'失去了意义并按原样使用。 Path.Combine(...) does not work here, since it does not add the path separator after a drive letter. Path.Combine(...)在这里不起作用,因为它没有在驱动器号后添加路径分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM