Reputation: 11
Creating a console app and I'm trying to set up a log file to keep track of the activities of my application. This is how I'm setting up my FileStream and Writer.
FileStream logstrm;
StreamWriter logwriter;
logstrm = new FileStream("file.txt", FileMode.OpenOrCreate, FileAccess.Write);
logwriter = new StreamWriter(logstrm);
Before calling SetOut, the following properly outputs the text to the console.
Console.WriteLine("LOG FILES CREATED");
However, once I do the following, I expect the text to be written to file.txt, but there is nothing in the file when I open it.
Console.SetOut(logwriter);
Console.WriteLine("TEXT EXPECTED TO BE IN FILE.TXT");
Any ideas or am I just doing this completely wrong?
Upvotes: 1
Views: 1348
Reputation: 1038
File I/O is buffered and may need to be flushed to actually write to the file.
You can explicitly flush to file by calling StreamWriter.Flush ; alternatively you could set AutoFlush so that the stream is flushed after every call to Write.
Files are automatically flushed on Close.
Upvotes: 1
Reputation: 116138
Simply you don't close the output file
logwriter.Close();
Either use Flush or Close the file
PS: Another test: You can continue to write to console till you exceed the internal buffer size and then you will see that some chars are written to file
Upvotes: 0