Hai’s Blog

January 5, 2008

How to Redirect Console Output to a File in C#

Filed under: Programming, Windows — Hai @ 2:43 am

I encountered the need to redirect the console output to a file in my attempt to automate testing of functions which does not return any value but writes to the console. Basically, we need to save the old output (Console.Out) before assigning the output to a file stream by means of Console.SetOut(). After the test, I also need to restore the console output.

After doing this for a while, it gets old and I told myself, “Self, I can create a simple class to simplify this task.” In my vision, output redirect should be easy, simple, and practical. The user should not have to remember the details such as which data type to use (TextWriter, FileStream, StreamWriter, …), or which steps to take. Thus, I created OutToFile, a simple class which encapsulate this idea. Using OutToFile is … you guessed it, easy:

Console.WriteLine(“This goes to console”);

using (new OutToFile(“output.txt”)) // redirect the output to a text file
{
    Console.WriteLine(“This text goes to a file”);
} // redirection ends upon exiting the using block

Console.WriteLine(“This goes back to console”);

The source code for this class is available, you are free to use it, but I reserve the bragging right :-) .

Blogged with Flock

Tags: , ,

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.