Quick tip : redirect the console output to a file

In a console application, we use a lot the Console.WriteLine method.

We can redirect the output of the WriteLine method easily :

var consoleOut = Console.Out; // save the current output stream to be able to re-use it later

Console.SetOut(File.CreateText(@"C:\consoleout.txt")); // change the output stream for a file
 Console.WriteLine("a sample text"); // write some information

Console.SetOut(consoleOut); // reset the output to the console.

About Sam Beauvois

Application Developer, .NET enthusiast since 2004, I'm interested in technology watch, usability, code quality, patterns & practices, UX, ...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>