How can I immediately write to a file?

I want to save a log file, and I use TextWriter / StreamWriter to write messages to my log file. I call TextWriter.Flush () after recording the message, but my message still does not appear immediately. It appears only when Close is called, and I would prefer not to open and close the file all the time to immediately see the messages.

+4
source share
3 answers

You might want to try creating a FileStream yourself by passing it to the FileOptions.WriteThrough constructor. Then create a StreamWriter using FileStream. The WriteThrough parameter bypasses the cache.

+4
source

You can also set the StreamWriter.AutoFlush property to true. In this case, everything that is recorded in StreamWriter will be written to disk immediately (after each call to Write ).

From the MSDN documentation in AutoFlush:

Gets or sets a value indicating whether the StreamWriter will flush its buffer into the underlying stream after each call to StreamWriter..Write.

Mark

+3
source

Make sure that you open the log file with shared access, allowing all subsequent openings of the file for reading, but denying write access. Thus, you can track the log from another program.

0
source

All Articles