【发布时间】: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