C# Console.SetOut and Console.SetInThese C# examples use Console.SetOut and SetIn. SetOut changes the target output of a console application.
Console.SetOut. A console program can write its output to a file. With the Console.SetOut method, we specify a StreamWriter as the output object.
Then, when the program executes, all the Console.Write calls will be printed to the file. We can also use Console.SetIn to adjust the input source.
With this program, we create a new StreamWriter in a using-statement. Then we use the SetOut method and pass the StreamWriter instance to it.
And: After this point, all the Console.WriteLine calls are printed to the file C:\out.txt.Using
Tip: It might be better for this program to omit the using resource acquisition statement.
Instead: The StreamWriter could be disposed of when the program exits automatically. This approach would reduce the code complexity.
C# program that uses Console.SetOut
static void Main()
using (StreamWriter writer = new StreamWriter("C:\\out.txt"))
static void Act()
Console.WriteLine("This is Console.WriteLine");
Console.WriteLine("Thanks for playing!");
This is Console.WriteLine
Thanks for playing!
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.
Tip: StreamWriter is more useful for writing text to files. TextWriter is mostly needed for interoperability.TextWriterStreamWriter
SetIn example. We can also use Console.SetIn to set the input source—we can use to automate calls such as a Console.ReadLine. Streams can be dynamically modified in the .NET Framework.
C# program that uses Console.SetIn
static void Main()
using (StreamReader reader = new StreamReader("C:\\programs\\file.txt"))
static void X()
string line = Console.ReadLine();
Console.WriteLine("READLINE RETURNED: " + line);
READLINE RETURNED: HELLO WORLD!
Summary. We used the Console.SetOut method for changing the target of the output of a console program. We also used SetIn to change the input source.
SetOut 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.WriteLine
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.