Charles Okwuagwu
Charles Okwuagwu

Reputation: 10866

Copy all lines of a console app screen to text file

I have a console application that does a lot of logging to screen via Console.Writeline.

Short of converting each Console.Writeline to a file write, or buffering each console.Writeline to a StringBuilder,

is there a way to take a full dump of the console screen lines to a text file when the application runs to the end?

Upvotes: 0

Views: 3443

Answers (2)

backtrack
backtrack

Reputation: 8144

  FileStream ostrm;
            StreamWriter writer;
            TextWriter oldOut = Console.Out;
            try
            {
                ostrm = new FileStream("./Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);
                writer = new StreamWriter(ostrm);
            }
            catch (Exception e)
            {
                Console.WriteLine("Cannot open Redirect.txt for writing");
                Console.WriteLine(e.Message);
                return;
            }
            Console.SetOut(writer);
            Console.WriteLine("This is a line of text");
            Console.WriteLine("Everything written to Console.Write() or");
            Console.WriteLine("Console.WriteLine() will be written to a file");
            Console.SetOut(oldOut);
            writer.Close();
            ostrm.Close();
            Console.WriteLine("Done");

use can use Console.SetOut() to set the output

nice example : http://www.java2s.com/Code/CSharp/Development-Class/DemonstratesredirectingtheConsoleoutputtoafile.htm

Upvotes: 1

KMoussa
KMoussa

Reputation: 1578

You can either:

1- Redirect Console.WriteLine to a file:

System.IO.FileStream fs = new System.IO.FileStream(@"C:\Output.txt", System.IO.FileMode.Create);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
System.Console.SetOut(sw);

(PS. If you do so, don't forget to set the Console output back and close the stream before the program terminates)

2- When running your executable, direct the output to a file, for example:

C:\>MyExecutable.exe > C:\Output.txt

Upvotes: 4

Related Questions