Is it possible to intercept Console output?

前端 未结 1 763
终归单人心
终归单人心 2020-11-29 04:16

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.

相关标签:
1条回答
  • 2020-11-29 05:13

    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 讨论(0)
提交回复
热议问题