开发者

Is it possible to intercept Console output?

开发者 https://www.devze.com 2023-03-06 14:06 出处:网络
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.

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.

Is it possible for me开发者_StackOverflow社区 to intercept the output being generated by the FizzBuzz method? Note that my application is a Console app itself.


Yes, very much possible:

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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消