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?
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
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.