i am trying to to check if a log file with the same name exist and if it does, i want to append in the current log file but if does not exist i want to make a new one with the current date when the app is running. The problem is when i try to append to my already existent log file, the log file becomes empty.
string logFileLocation = Application.UserAppDataPath + "\\ cvDiagnostics_log_30-01-2022.text";
StreamWriter logFileStream = new StreamWriter(new FileStream(logFileLocation, FileMode.Create));
List<OutputEntry> outputMessages = new List<OutputEntry>();
outputMessages.AddRange(logInfoOutputMessages);
outputMessages.AddRange(logDebugOutputMessages);
outputMessages.AddRange(logWarningOutputMessages);
outputMessages.AddRange(logErrorOutputMessages);
outputMessages = outputMessages.OrderBy(e => e.DisplayedTimeStamp).ToList();
logFileStream.WriteLine( DateTime.Now.ToString());
foreach (var message in outputMessages)
{
logFileStream.WriteLine(message.ToString());
}
Here is my trying to check and append on an existing log file:
if (File.Exists(logFileLocation))
{
File.AppendAllText(logFileLocation, outputMessages.ToString());
}
}
else
{
File.Create(logFileLocation + DateTime.Now.ToString());
}
>Solution :
To open the file, you open a FileStream with FileMode.Create. This will truncate the file if it already exists.
StreamWriter logFileStream = new StreamWriter(new FileStream(logFileLocation, FileMode.Create));
Change this to:
StreamWriter logFileStream = new StreamWriter(new FileStream(logFileLocation, FileMode.Append));
From the documentation on FileMode.Create:
"Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown."