是否有可能拦截控制台输出?
问题描述:
我所说的方法,比方说, FizzBuzz()
,在这我管不着。使用这个方法输出一堆东西到控制台 Console.WriteLine
。
I call a method, say, FizzBuzz()
, over which I have no control. This method outputs a bunch of stuff to the Console using Console.WriteLine
.
是否有可能对我来说,拦截由 FizzBuzz
方法生成的输出?
请注意,我的应用程序是一个控制台应用程序本身。
Is it possible for me to intercept the output being generated by the FizzBuzz
method?
Note that my application is a Console app itself.
答
是的,很可能的:
var consoleOut = new StringWriter();
Console.SetOut(consoleOut);
Console.WriteLine("This is intercepted."); // This is not written to console
File.WriteAllText("ConsoleOutput.txt", consoleOut.ToString());
后来,如果要停止截获控制台输出,使用如下修改:
Later on if you want to stop intercepting the console output, use modification below:
var stdOut = Console.Out;
// Above interceptor code here..
Console.SetOut(stdOut); // Now all output start going back to console window
还是 OpenStandardOutput 做,而不需要先保存标准流是相同的:
Or the OpenStandardOutput does the same without the need to save the standard stream first:
// Above interceptor code here..
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput); // Now all output starts flowing back to console