是否有可能拦截控制台输出?有可能、控制台

2023-09-02 01:35:17 作者:内心独白

我所说的方法,比方说, FizzBu​​zz(),在这我管不着。使用这个方法输出一堆东西到控制台 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.

是否有可能对我来说,拦截由 FizzBu​​zz 方法生成的输出? 请注意,我的应用程序是一个控制台应用程序本身。

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