Home
C#
Console.SetOut and Console.SetIn
Updated Nov 19, 2023
Dot Net Perls
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.
Console.WriteLine
SetOut example. 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
Important The Console.SetOut method receives an object of type TextWriter. A StreamWriter can be implicitly cast to the TextWriter type.
TextWriter
StreamWriter
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!"); } }
This is Console.WriteLine Thanks for playing!
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.
using System; using System.IO; class Program { static void Main() { using (StreamReader reader = new StreamReader("C:\\programs\\file.txt")) { Console.SetIn(reader); X(); } } static void X() { string line = Console.ReadLine(); Console.WriteLine("READLINE RETURNED: " + line); } }
HELLO WORLD!
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 19, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen