Skip to content

Instantly share code, notes, and snippets.

@LGM-AdrianHum
Created February 8, 2016 03:44
Show Gist options
  • Save LGM-AdrianHum/f83d6850dacd50970ca6 to your computer and use it in GitHub Desktop.
Save LGM-AdrianHum/f83d6850dacd50970ca6 to your computer and use it in GitHub Desktop.
Redirect all output from the Console to a TextWriter
static public void Main ()
{
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");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment