Redirect Console Output in C#

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.WriteLine("Hello file");
Console.WriteLine("Hello World");

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: