Save Console.WriteLine output to a file with C#

A couple of days ago I created a console application that showed the results of operations were completed. After a few hours I realized that the information was becoming more and more and it was very difficult to read directly from the window, because the scroll, the oldest data had disappeared to make way for the new. The first thing that occurred to me was using Console.ReadLine(), but it was annoying to have to hit return whenever I wanted the program to continue moving forward. I didn’t want to modify the code and replace Console.WriteLine by Trace.TraceInformation, because I understood that the information was not to be a trace but show operations. Finally I decided to keep all information that was showing Console.WriteLine using a plain text file.

Save Console.WriteLine output to a file with C#

As you can imagine, you can change the output of the Console class, which by default displays information on the screen, so that it is stored, for example, in a file.

using System;
using System.IO;

namespace ConsoleApplicationChangeOutputStream
    class Program
        static void Main(string[] args)
            if (args == null) throw new ArgumentNullException("args");

            //1. Get the name of the output file
            var fileName = args[0];

            //2. Create the file
            var file = new FileStream(fileName, FileMode.OpenOrCreate);

            //3. Save the standard output
            var standardOutput = Console.Out;

            //4. Testing the console before changing the output
            Console.WriteLine("Hello world from the console!");

            //5. Create a StreamWriter
            using (var writer = new StreamWriter(file))
                //6. Set the new output
                //7. Write something
                Console.WriteLine("Hello World from the file!");
                //8. Change the ouput again

            //9. Last testing
            Console.WriteLine("Here I am again!");

            //10. The end


As you can see in the code, I stored the current output in a variable, with the goal of restoring it in the future, I need to create a file with the name passed as parameter, using Debug > Command line arguments, and create a StreamWriter object to be assigned as output for the static class Console. From this moment, everything we send to the console application via Write or WriteLine not be shown in the window, but will be stored directly in the text file. Another alternative would be to combine both outputs so that we could display in real time the information is stored. You may also be interested in Log4Net for your applications, which makes use of this functionality.