Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate console output of self process

I'd like to redirect my process console output to file, while mantaining the utility of displaying it on the curretnly attached console.

The redirection is done easily with:

using (FileStream fs = new FileStream(TestLogName("Texture"), FileMode.Create, FileAccess.Write)) {
    Console.SetOut(new StreamWriter(fs));

    ...

    Console.Out.Flush();
}

But how I can achieve the same result while mantaining the console output on already attached console (de-facto duplicating the stream)?

like image 921
Luca Avatar asked Oct 20 '25 11:10

Luca


1 Answers

You can sub-class TextWriter with a class that writes to a file and another TextWriter class. Then initialize an instance of this class with the current value of System.Console.Out.

var writer = new SplitWriter(Console.Out, @"c:\temp\logfile.txt");
Console.SetOut(writer);

SplitWriter then takes responsibility for writing to both the file and the original value of Console.Out.

like image 84
colivier Avatar answered Oct 22 '25 23:10

colivier