Reputation: 177
My app takes selected information from a SQL database and puts it into a nicely column formatted text file. The problem I have is if the program crashes or stops for any reason, it will overwrite the previous text when restarted.
I'm trying to use the example provided by Microsoft here, but I can't seem to set it up right.
This is the method I'm using to write the text file
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()
Upvotes: 1
Views: 2539
Reputation: 61349
You won't be able to use File.WriteAllText
if you want to append, so I would do something like this:
StreamWriter sw;
if (!File.Exists(outputPath)
{
sw = new StreamWriter(outputPath, false);
sw.WriteLine(headers);
}
else
sw = new StreamWriter(outputPath, true);
foreach (...)
sw.WriteLine(dataLine);
You could initialize the StreamWriter
to always append on declaration, but it would have broken the "previous file exists" logic, so I set it up a bit different than usual.
As a side note, you are doing a lot of string concatenation, consider using StringBuilder
instead. If you stick with that approach, you could use File.AppendAllText
instead of writing each line individually in the foreach
. Note that this approach is very memory-inefficient compared to just writing each line to the file (thanks @Servy).
Also, if the program crashes, you'll have a "junk" line in the middle that will be non-trivial to detect (in order to put the newline in). You may want to always insert a new line before you start appending, even though that would cause a weird line break in the data under normal circumstances.
Upvotes: 2
Reputation:
Check whether file exists before placing the using the c# file exist function or create a new file with different name each time you run the application
Upvotes: 0