Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When i try to append text to a log file, my log file becomes empty

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());
        }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading