C# How to redirect stream to the console Out?

C#.NetConsole Application

C# Problem Overview


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");

C# Solutions


Solution 1 - C#

Just point the stream to standard output:

sw = new StreamWriter(Console.OpenStandardOutput());
sw.AutoFlush = true;
Console.SetOut(sw);

Solution 2 - C#

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://docs.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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoppity BopView Question on Stackoverflow
Solution 1 - C#John FeminellaView Answer on Stackoverflow
Solution 2 - C#Igal OreView Answer on Stackoverflow