47

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 to intercept the output being generated by the FizzBuzz method? Note that my application is a Console app itself.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
AngryHacker
  • 59,598
  • 102
  • 325
  • 594

1 Answers1

75

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
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 6
    Don't forget to save `Console.Out` before doing this so you can restore it. – Rick Sladkey May 16 '11 at 22:37
  • 4
    @Rick: Unless someone has already switched it out! :) `Console.OpenStandardOutput()` will always give you the real one. – porges May 16 '11 at 23:05
  • @Porges: If `FizzBuzz` has the same point of view we are out of luck :-) – Rick Sladkey May 16 '11 at 23:07
  • 3
    @Teoman Soygul: worth noting, that this only works if FizzBuzz is executed in the same appdomain. It most likely not an issue for the OP, just noting, for completeness. – Andrew Savinykh May 16 '11 at 23:11
  • @Teoman: you need to set it using `SetOut` as well, that just retrieves the stream. – porges May 17 '11 at 00:52
  • 2
    What about intercepting colored output: i.e.: `var oldColor = Console.ForegroundColor; Console.ForegroundColor = color ?? oldColor; Console.Write(message); Console.ForegroundColor = oldColor;` – bushed Jul 06 '12 at 17:53
  • @Porges: Following the "what if everyone did this?" rule, it is often better to save and restore `Console.Out` than to use `Console.OpenStandardOutput()`. Like the OP's program, any other utility which swapped out `Console.Out` may have a dependency on that behavior. – Brian Jan 20 '15 at 17:57
  • I assume this won't work if the Console output is coming from a native library called from .NET wrapper library called from my code, right? – Patrick Szalapski Jan 26 '21 at 22:48