
You have a C# console program and want to write its output to a text file. With the Console.SetOut method, you can specify a StreamWriter as the output object, and then when the program executes all the Console.Write calls will be printed to the file.
With this program, we create a new StreamWriter object in a resource acquisition statement. Then, we use the SetOut method and pass the StreamWriter instance to it. After this point, all the Console.WriteLine calls will not be printed to the console; instead, they will be printed to the file C:\out.txt.
This C# example program uses Console.SetOut. This method changes the target output of a console application.
Program that uses Console.SetOut [C#]
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("C:\\out.txt"))
{
Console.SetOut(writer);
Act();
}
}
static void Act()
{
Console.WriteLine("This is Console.WriteLine");
Console.WriteLine("Thanks for playing!");
}
}
Contents of file [C:\out.txt]
This is Console.WriteLine
Thanks for playing!Note. It might be better for this program not to use the using resource acquisition statement. The StreamWriter could be disposed of when the program exits automatically. This approach would reduce the complexity of the source code a bit.

The Console.SetOut method receives an object of type TextWriter. The StreamWriter can be passed to Console.SetOut and it is implicitly cast to the TextWriter type. This is because StreamWriter is derived from TextWriter.
Using TextWriter Using StreamWriterWe looked at the Console.SetOut method in the C# language for changing the target of the output of a console program. This allows you to save the output of a Console program to a file without modifying the uses of the Console.Write and Console.WriteLine calls.
Console Programs