Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to intercept Console output?

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.

like image 304
AngryHacker Avatar asked May 16 '11 22:05

AngryHacker


People also ask

How do I display console output?

Press CTRL + F5 to see your output. This will wait the console screen until you press any key.

What is the line to print output to the console?

To print a message to the console, we use the WriteLine method of the Console class. The class represents the standard input, output, and error streams for console applications. Note that Console class is part of the System namespace. This line was the reason to import the namespace with the using System; statement.


1 Answers

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 
like image 75
Teoman Soygul Avatar answered Sep 22 '22 23:09

Teoman Soygul