0

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());
        }
  • you're using FileMode.Create instead FileMode.Append – J.Salas Jan 27 '22 at 10:08
  • You need to pass `append:true` to the StreamWriter constructor *and* use `FileMode.Append`. The real solution though is to use a logging library, eg Serilog. Logging is far more complex than just appending lines to a text file. For example, how are you going to handle those *localized* strings? Unless your locale uses ISO8601 (none does) you won't be able to sort by date. What about multiple threads writing to the log? You could end up with exceptions or corrupted data – Panagiotis Kanavos Jan 27 '22 at 10:08

1 Answers1

0

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."

jeroenh
  • 26,362
  • 10
  • 73
  • 104