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)
{
	RunStandardOutRedirectExample();
}

private static void RunStandardOutRedirectExample()
{
	StringBuilder builder = new StringBuilder();
	TextWriter writer = new StringWriter(builder);
	Console.SetOut(writer);

	for (int i = 0; i < 10; i++)
	{
		Console.WriteLine(GetRandomString(5));
		Thread.Sleep(100);
	}

	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:

FHIHZ
KlsKv
HkCYG
NOnbd
ednTd
QshsL
uHikL
eGeyW
xkcBs
CONFP

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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: