【问题标题】:How to repeatedly generate output file with same name如何重复生成具有相同名称的输出文件
【发布时间】:2021-02-28 18:11:21
【问题描述】:

我有一项服务可以为每次迭代运行生成多个输出文件。它每天运行一次。输出文件名始终保持不变,旧文件被删除,然后被新文件替换。 例如:

为今天的迭代生成的输出文件将是

  • abc.txt
  • def.txt
  • ghi.txt

为明天迭代生成的输出文件将删除旧文件并创建新文件

  • abc.txt
  • def.txt
  • ghi.txt

我正在使用以下函数来实现我所说的。

public static void CreateOutputFile(string Message, string fileName)
{
    try
    {
        string filePath = ConfigurationManager.AppSettings["DESTDIRPATH"] + Path.DirectorySeparatorChar + fileName;
        if (File.Exists(filePath)) //Check if file exists if yes then compare last modified date and delete the older file
        {
            DateTime dateTime = File.GetLastWriteTime(filePath);
            if (dateTime < System.DateTime.Now.AddHours(-5))
            {
                File.Delete(filePath);
            }
        }
        
        if (!File.Exists(filePath)) //Check if file exists if yes then append else create a new file.
        {
            using (StreamWriter sw = File.CreateText(filePath))
            {
                sw.WriteLine(Message);
            }
        }
        else
        {
            using (StreamWriter sw = File.AppendText(filePath))
            {
                sw.WriteLine(Message);
            }
        }
    }
    catch (Exception ex)
    {
        WriteToFile(ex.Message);
    }
}

这很好用,但我确信上面的 sn-p 必须有更好/优化/改进的代码。所以请让我知道你的建议。

谢谢。

【问题讨论】:

    标签: c# optimization


    【解决方案1】:

    一个建议是将包含对 File.CreateText 和 FileAppendText 的调用的 IF 块替换为对 StreamWriter 的单个调用。这两种方法都是调用 StreamWriter 的包装器方法。唯一不同的是它们为附加标志传递的内容。在您的情况下,如果文件存在或创建文件,则附加值将为 true。

    示例 1:

            //Check if file exists if yes then compare last modified date and delete the older file
            if (File.Exists(filePath))
            {
                DateTime dateTime = File.GetLastWriteTime(filePath);
                if (dateTime < System.DateTime.Now.AddHours(-5))
                {
                    File.Delete(filePath);
                }
            }
    
            using (StreamWriter sw = new StreamWriter(filePath,true))
                sw.WriteLine(Message);
    

    示例 2:利用其他文件访问选项:

            using (FileStream fs = new FileStream(filePath,             // File full path
                                                  FileMode.Append,      // Open for append or create
                                                  FileAccess.Write,     // Write mode only
                                                  FileShare.ReadWrite)) // Open for Shared Read/Write access
            using (StreamWriter sw = new StreamWriter(fs))
                sw.WriteLine(Message);
    

    请参阅File.cs 了解 File.CreaeText 和 File.AppendText 源代码实现。

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 2011-01-27
      • 2021-08-14
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 2018-05-09
      相关资源
      最近更新 更多