C# How to redirect stream to the console Out?

一个人想着一个人 提交于 2019-11-30 07:22:48

问题


I found lots of samples how to redirect console output into a file. However I need an opposite solution - I have StreamWriter which I want to be shown in the Console output once I do sw.WriteLine("text");


回答1:


Just point the stream to standard output:

sw = new StreamWriter(Console.OpenStandardOutput());
sw.AutoFlush = true;
Console.SetOut(sw);



回答2:


Not that previous answer not correct, but since i do not have enough reputation level to add comment, just adding another answer:

If you would ever use pointing Stream to standard output as John proposed with using statement you should not forget to re-open console Stream later on, as explained in https://docs.microsoft.com/en-us/dotnet/api/system.console.setout?view=netframework-4.7.2

using (sw = new StreamWriter(Console.OpenStandardOutput())
{
    sw.AutoFlush = true;
    Console.SetOut(sw);
    ...
}
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);


来源:https://stackoverflow.com/questions/3127498/c-sharp-how-to-redirect-stream-to-the-console-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!