TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Console.SetOut: File Output

This C# example program uses Console.SetOut. This method 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.

Console.WriteConsole.WriteLine

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. 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 not to use 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 of file

This is Console.WriteLine
Thanks for playing!

TextWriter. 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.

Tip: StreamWriter is more useful for writing text to files. TextWriter is mostly needed for interoperability.

TextWriterStreamWriter

Summary. We used the Console.SetOut method 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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf