如何追加到使用循环的文本文件
本文关键字:循环 文本 文件 何追加 追加 | 更新日期: 2023-09-27 18:36:12
我的应用从 SQL 数据库中获取所选信息,并将其放入列格式良好的文本文件中。我遇到的问题是,如果程序因任何原因崩溃或停止,它将在重新启动时覆盖以前的文本。
我正在尝试在此处使用 Microsoft 提供的示例,但我似乎无法正确设置它。
这是我用来编写文本文件的方法
private void Output()
{
string createText =
FormatWidth("Severity", 10) +
FormatWidth("LastNotification", 18) +
FormatWidth("FirstNotification", 18) +
FormatWidth("DeviceIP", 18) +
FormatWidth("DeviceInterface", 20) +
"DescriptionShort";
foreach (KeyValuePair<string, AlarmData> AlarmDataText in AlarmDictionary)
{
createText += Environment.NewLine;
createText +=
FormatWidth(AlarmDataText.Value.eventSeverity, 8) +
FormatWidth(AlarmDataText.Value.eventLastNotification.ToString("yyyy-MM-dd HH:mm"), 18) +
FormatWidth(AlarmDataText.Value.eventFirstNotification.ToString("yyyy-MM-dd HH:mm"), 18) +
FormatWidth(AlarmDataText.Value.deviceIP, 18) +
FormatWidth(AlarmDataText.Value.deviceInterface, 20) +
AlarmDataText.Value.descriptionShort;
}
File.WriteAllText("C:''Users''*username*''Documents''Visual Studio 2010''Projects''NMS_Logger''NMS_Logger''bin''Log.txt", createText);
Console.WriteLine("File Updated"); //For working verification
}//end Output()
如果你想
追加,你将无法使用File.WriteAllText
,所以我会做这样的事情:
StreamWriter sw;
if (!File.Exists(outputPath)
{
sw = new StreamWriter(outputPath, false);
sw.WriteLine(headers);
}
else
sw = new StreamWriter(outputPath, true);
foreach (...)
sw.WriteLine(dataLine);
您可以将StreamWriter
初始化为始终追加声明,但它会破坏"以前的文件存在"逻辑,因此我的设置与平时略有不同。
作为旁注,您正在执行大量字符串连接,请考虑改用StringBuilder
。如果您坚持使用这种方法,则可以使用File.AppendAllText
而不是在foreach
中单独编写每一行。请注意,与仅将每一行写入文件相比,此方法的内存效率非常低(谢谢@Servy)。
此外,如果程序崩溃,您将在中间有一个"垃圾"行,这将非常容易检测到(以便放入换行符)。您可能希望在开始追加之前始终插入新行,即使这在正常情况下会导致数据中出现奇怪的换行符。
在放置使用 c# 文件存在函数之前检查文件是否存在,或者在每次运行应用程序时创建具有不同名称的新文件