Console.SetOut到StreamWriter,不断写入文本文件
我正在使用 Console.SetOut 方法将所有 Console.Out.WriteLines 写入文件,这有效。唯一的问题是,当我关闭应用程序时,它只会将所有内容写入文本文件,而不是在发生 Console.Out.WriteLine 时写入。 关于如何实现这一点有什么想法吗?
我是怎么做的: 在Application.Run()之前;
FileStream writerOutput = new FileStream("Logging_Admin.txt", FileMode.Append, FileAccess.Write);
StreamWriter writer = new StreamWriter(writerOutput);
Console.SetOut(writer);
在 Application.Run() 之后:
writer.Dispose();
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
StreamWriter 有一个 AutoFlush 属性。当设置为 true 时,您应该得到您需要的结果。
StreamWriter has an AutoFlush property. When set to true, you should get the result you need.
默认情况下,
StreamWriter
将缓冲其内容。如果要刷新缓冲区,则必须调用冲洗
方法:The
StreamWriter
will buffer its contents by default. If you want to flush the buffer you must call theFlush
method:如果您不想每次都手动调用刷新,您可能需要考虑实现您自己的 TextWriter 派生对象来为您执行此操作。
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.
要刷新缓冲区,你可以这样做
作者.关闭();
To flush the buffer, you can do
writer.Close();