[英]Why wont console.SetOut(StreamWriter) write to my file?
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和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. 在调用SetOut之前,以下内容正确地将文本输出到控制台。
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. 但是,一旦我执行以下操作,我希望将文本写入file.txt,但是当我打开它时文件中没有任何内容。
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 使用Flush或Close文件
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 PS:另一个测试:您可以继续写入控制台,直到超过内部缓冲区大小,然后您将看到一些字符写入文件
File I/O is buffered and may need to be flushed to actually write to the file. 文件I / O是缓冲的,可能需要刷新才能实际写入文件。
You can explicitly flush to file by calling StreamWriter.Flush ; 您可以通过调用StreamWriter.Flush显式刷新到文件; alternatively you could set AutoFlush so that the stream is flushed after every call to Write.
或者,您可以设置AutoFlush,以便在每次调用Write后刷新流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.