GuillaumeA
GuillaumeA

Reputation: 3545

Writing log file while reading it with Excel or Notepad

I'm writing to a log file with this stream :

using(FileStream fs = new FileStream(Path.Combine(Folder, LogFile),
                                      FileMode.OpenOrCreate,
                                      FileAccess.Write,
                                      FileShare.ReadWrite))
{
   using(System.IO.StreamWriter file = new System.IO.StreamWriter(fs))
   {
      while(!token.IsCancellationRequested)
      {          
         file.WriteLine("bla bla bla");
      }
   }
}

The purpose of this code sample is to write into a log file. What I would like to be able to do is to read it with Excel or notepad while this code is running. I can open the file externally with Excel, but the file is empty until I stop the program. Furthermore, when I try to open it with Excel, I am said that the file is locked for editing although I declared the stream with the FileShare.ReadWrite.

Upvotes: 1

Views: 326

Answers (1)

MethodMan
MethodMan

Reputation: 18843

when writing files in a while loop and you want to see the data real time for example in NotePad you need to immediately Flush the data in your case a simple

file.Flush(); 

inside of the while loop after the file.Write will work

using(FileStream fs = new FileStream(Path.Combine(Folder, LogFile),
                                      FileMode.OpenOrCreate,
                                      FileAccess.Write,
                                      FileShare.ReadWrite))
{
   using(System.IO.StreamWriter file = new System.IO.StreamWriter(fs))
   {
      while(!token.IsCancellationRequested)
      {          
         file.WriteLine("bla bla bla");
         file.Flush();
      }
   }
}

Upvotes: 1

Related Questions