Those of you that know me know that I love a good console application. I use them all the time for samples and prototypes. Sometimes it’s nice to capture the output from a console application to share with others.
It’s remarkably simple to accomplish this with the .NET Framework. There is a static method Console.SetOut that accepts a TextWriter. Redirecting output from your console application is as simple as creating a TextWriter and calling that method.
Here’s a quick example (taken directly from MSDN):
Console.WriteLine("Hello World"); FileStream fs = new FileStream("Test.txt", FileMode.Create); // First, save the standard output. TextWriter tmp = Console.Out; StreamWriter sw = new StreamWriter(fs); Console.SetOut(sw); Console.WriteLine("Hello file"); Console.SetOut(tmp); Console.WriteLine("Hello World"); sw.Close();