6

I'm using the Console.SetOut method to write all my Console.Out.WriteLines to a file, and this works. The only problem is that it only writes everything to the textfile when I close my application instead of it writing whenever a Console.Out.WriteLine happens. Any ideas on how I can realise this?

How I do it: Before Application.Run();

FileStream writerOutput = new FileStream("Logging_Admin.txt", FileMode.Append, FileAccess.Write);
StreamWriter writer = new StreamWriter(writerOutput);
Console.SetOut(writer);

After Application.Run():

writer.Dispose();

Thanks.

Fverswijver
  • 459
  • 1
  • 12
  • 30

4 Answers4

13

StreamWriter has an AutoFlush property. When set to true, you should get the result you need.

Jens
  • 25,229
  • 9
  • 75
  • 117
11

The StreamWriter will buffer its contents by default. If you want to flush the buffer you must call the Flush method:

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
1

If you don't want to call flush every time manually, you might want to consider implementing your own TextWriter-derived object to do this for you.

David Morton
  • 16,338
  • 3
  • 63
  • 73
0

To flush the buffer, you can do writer.Close();

LeMoussel
  • 5,290
  • 12
  • 69
  • 122