tags:

views:

112

answers:

3

I want to keep a logfile, and I am using TextWriter/StreamWriter to write messages to my logfile. I call TextWriter.Flush() after writing the message, but my message still doesn't show up right away. It only shows up when I call Close, and I would rather not reopen and close the file all of the time just to see messages immediately.

+2  A: 

You might want to try constructing a FileStream yourself passing in the FileOptions.WriteThrough to the constructor. Then construct your StreamWriter with that FileStream. The WriteThrough option bypasses the cache.

Mike Two
This method was the only one that worked 100% of the time, thanks.
esac
A: 

Make sure you open your log file with the read-share access, allowing all subsequent openings of the file for reading, but denying the write access. This way you will be able to monitor the log from another program.

Yurik
A: 

You could also set the StreamWriter.AutoFlush property to true. With this, anything written to the StreamWriter will be written to disk right away (after every call to Write).

From the MSDN documentation on AutoFlush:

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

Marc

marc_s