How to redirect standard error output for a .NET console application

Normally a .NET console application writes its exception messages directly to the console so that the user can view them.

Here’s an example:

static void Main(string[] args)
{
	RunStandardErrorRedirectExample();			
	Console.ReadKey();
}

private static void RunStandardErrorRedirectExample()
{
	try
	{
		double res = Divide(100, 0);
		Console.WriteLine(res);
	}
	catch (Exception ex)
	{
		using (TextWriter errorWriter = Console.Error)
		{
			errorWriter.WriteLine(ex.Message);
		}
	}
}

private static double Divide(int divideWhat, int divideBy)
{
	return divideWhat / divideBy;
}

You’ll get “Attempted to divide by 0” in the console.

However, this is not the only option you have. The standard error 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 StreamWriter, i.e. we’ll tell the console to “write the lines” to a file instead of the default console. The Console.SetError method is the most important method to remember if you want to redirect the standard error output.

The following example will put the exception messages to a file called errors.txt:

private static void RunStandardErrorRedirectExample()
{
	FileInfo exceptionsFile = new FileInfo(@"c:\errors.txt");
	TextWriter exceptionWriter = new StreamWriter(exceptionsFile.FullName);
	Console.SetError(exceptionWriter);
	try
	{
		double res = Divide(100, 0);
		Console.WriteLine(res);
	}
	catch (Exception ex)
	{
		using (TextWriter errorWriter = Console.Error)
		{
			errorWriter.WriteLine(ex.Message);
		}
	}
}

If you’d like to reset the error output to the console again then you can do it as follows:

Console.SetError(new StreamWriter(Console.OpenStandardError()));

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

iReadable { }

.NET Tips & Tricks

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: