How to redirect standard error output for a .NET console application
March 22, 2016 1 Comment
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.
Hi Andras,
I am getting 301 move permanently error in my C#/VB app, can i redirect this error and how?
thanks