66

I found lots of samples how to redirect console output into a file. However I need an opposite solution - I have StreamWriter which I want to be shown in the Console output once I do sw.WriteLine("text");

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151
  • I'm a little confused. What is the stream initialized to, if not `Console.Out`? Is it writing both to a file _and_ to the console? – John Feminella Jun 27 '10 at 13:45

2 Answers2

121

Just point the stream to standard output:

sw = new StreamWriter(Console.OpenStandardOutput());
sw.AutoFlush = true;
Console.SetOut(sw);
John Feminella
  • 303,634
  • 46
  • 339
  • 357
10

Not that previous answer not correct, but since i do not have enough reputation level to add comment, just adding another answer:

If you would ever use pointing Stream to standard output as John proposed with using statement you should not forget to re-open console Stream later on, as explained in https://learn.microsoft.com/en-us/dotnet/api/system.console.setout?view=netframework-4.7.2

using (sw = new StreamWriter(Console.OpenStandardOutput())
{
    sw.AutoFlush = true;
    Console.SetOut(sw);
    ...
}
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Igal Ore
  • 301
  • 4
  • 8
  • 1
    I think you misunderstood the sample code in the link you provided.. Wont downvote you. I appreciate your effort :) – Boppity Bop Dec 05 '18 at 08:56