每次在c#中写入新文件

问题描述 投票:-3回答:3

我正在研究一个c#控制台应用程序。我将一些数据保存到文本文件中。每次运行程序时,它都会将数据保存到该文件中而不会覆盖它。现在我想在每次发送请求/运行新程序时将数据保存到新文件中。

var result = XmlDecode(soapResult);
XDocument doc = XDocument.Parse(result);

XmlReader read = doc.CreateReader();
DataSet ds = new DataSet();
ds.ReadXml(read);
read.Close();

if (ds.Tables.Count > 0 && ds.Tables["Reply"] != null && ds.Tables["Reply"].Rows.Count > 0)
{
    string refNo = string.Empty;
    string uniqueKey = string.Empty;
    string meterNo = string.Empty;
    List<string> ls = new List<string>();
    if (ds.Tables["Reply"].Rows[0][0].ToString().ToUpper() == "OK")
    {

        if (ds.Tables["Names"] != null && ds.Tables["Names"].Rows.Count > 0)
        {
            uniqueKey = ds.Tables["Names"].Rows[0]["name"].ToString();
        }

        if (ds.Tables["NameType"] != null && ds.Tables["NameType"].Rows.Count > 0)
        {
            refNo = ds.Tables["NameType"].Rows[0]["name"].ToString();
        }

        if (ds.Tables["Meter"] != null && ds.Tables["Meter"].Rows.Count > 0)
        {
            if (ds.Tables["Meter"].Columns.Contains("mRID"))
            {
                meterNo = ds.Tables["Meter"].Rows[0]["mRID"].ToString();
                processedRec++;
            }


        }
    }
    log = uniqueKey + " | " + refNo + " | " + meterNo + " | " + Environment.NewLine;
    ls.Add(log);
}
File.AppendAllText(filePath, log);

我怎样才能每次都创建一个新文件?

任何帮助将受到高度赞赏。

c# .net file
3个回答
0
投票

创建一个唯一的filePath。像这样的东西:

var filePath =$"{folderPath}\txtFile_{Guid.NewGuid()}"; 

这将使文件始终是唯一的。 guid可以替换为更有意义的东西,如Unix时间戳。


0
投票

每次创建一个自定义文件名并使用File.WriteAllText(它将创建一个新文件,将内容写入文件,然后关闭文件。如果目标文件已经存在,则会被覆盖。)而不是File.AppendAllText

在你的情况下,filePath应该是动态的,可以像这样构造:

string basePath = ""; // this should be path to your directory in which you wanted to create the output files
string extension = ".xml";
string fileName = String.Format("{0}{1}{2}","MyFile",DateTime.Now.ToString("ddMMyy_hhmmss"),extension ); 
string filePath = Path.Combine(basePath,fileName); 

在上面的代码片段中,DateTime.Now.ToString("ddMMyy_hhmmss")将是当前时间(在执行代码时),每次执行都会有所不同,因此文件名在每次运行时都会有所不同。在稍后的某些时间点,您可以根据这些常见模式搜索/分组文件。

还有一件事:

在您的代码中,您使用了一个填充了所有日志的变量List<string> ls,并且您正在将log的内容写入该文件,该文件仅包含最后一条记录。所以写内容的声明应该是:

File.WriteAllText(filePath, String.Join("\n",log));

甚至简单地说

File.WriteAllLines(filePath, log);

0
投票

只需使您的filePath唯一,例如使用Ticks

var filePath = $"app-log-{DateTime.Now.Ticks:X}.log";
© www.soinside.com 2019 - 2024. All rights reserved.