How to redirect standard output for a .NET console application

Normally a .NET console application writes its messages directly to the console so that the user can view them. This is done with one of the “Write” methods like Console.WriteLine(some message) where you can prompt the user for some input.

However, this is not the only option you have. The standard output channel can be overridden.

All you need is an object which derives from the abstract TextWriter class. There are a couple of classes in .NET that derive from this base class, such as StringWriter which stores the text in a StringBuilder object and StreamWriter which saves the text to a file.

We’ll look at an example using StringWriter, i.e. we’ll tell the console to “write the lines” to a StringBuilder instead of the default console. The Console.SetOut method is the most important method to remember if you want to redirect the standard output.

The following example will generate 10 random strings with a small pause in between each random string. Standard output is redirected to a StringWriter hence Console.WriteLine won’t output the messages to the console but the StringBuilder that was added to the StringWriter constructor:

static void Main(string[] args)

private static void RunStandardOutRedirectExample()
	StringBuilder builder = new StringBuilder();
	TextWriter writer = new StringWriter(builder);

	for (int i = 0; i < 10; i++)

	string result = builder.ToString();

private static string GetRandomString(int size)
	Random random = new Random();
	string charSet = "abcdefghijklmnopqestuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	char[] buffer = new char[size];
	for (int i = 0; i < size; i++)
		buffer[i] = charSet[random.Next(charSet.Length)];
	return new string(buffer);

Here’s an example of what “result” could look like:


The StreamWriter class will help you save all that in a file instead.

If you’d like to reset Console.WriteLine to write the messages to the console then insert the following bit of code:

Console.SetIn(new StreamReader(Console.OpenStandardOutput()));

View all various C# language feature related posts here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: