C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: After this point, all the Console.WriteLine calls are printed to the file C:\out.txt.
UsingTip: 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
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 (out.txt):
This is Console.WriteLine
Thanks for playing!
Tip: StreamWriter is more useful for writing text to files. TextWriter is mostly needed for interoperability.
TextWriterStreamWriterC# program that uses Console.SetIn
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);
}
}
Contents (file.txt):
HELLO WORLD!
Output
READLINE RETURNED: HELLO WORLD!