C# StreamWriter Example

StreamWriter class in C# writes characters to a stream in a specified encoding. StreamWriter.Write method is responsible for writing text to a stream.

StreamWriter class in C# writes characters to a stream in a specified encoding. StreamWriter.Write() method is responsible for writing text to a stream. StreamWriter class is inherited from TextWriter class that provides methods to write an object to a string, write strings to a file, or to serialize XML.
 
StreamWriter is defined in the System.IO namespace. StreamWriter provides the following Write methods,
  1. Write – Writes data to the stream.
  2. WriteAsync - Writes data to the stream asynchronously.
  3. WriteLine – Writes a line terminator to the text string or stream.
  4. WriteLineAsync - Writes a line terminator to the text string or stream asynchronously.
  5. Creating a StreamWriter using a Filename
CSharp StreamWriter
 
StreamWriter constructor takes a file name or a FileStream object with Encoding, and buffer size as optional parameters.
 
The following code snippet creates a StreamWriter from a filename with default encoding and buffer size. 
  1. // File name  
  2. string fileName = @"C:\Temp\Mahesh.txt";  
  3. StreamWriter writer = new StreamWriter(fileName);  
The following code snippet creates a StreamWriter and adds some text to the writer using StreamWriter.Write method. If the file does not exist, the writer will create a new file. If the file already exists, the writer will override its content.
  1. string fileName = @"C:\Temp\CSharpAuthors.txt";  
  2. try  
  3.    {  
  4.    using (StreamWriter writer = new StreamWriter(fileName))  
  5.       {  
  6.       writer.Write("This file contains C# Corner Authors.");  
  7.       }  
  8.    }  
  9. catch(Exception exp)  
  10.    {  
  11.       Console.Write(exp.Message);  
  12.    }  

Creating a StreamWriter using a FileStream

 
StreamWriter constructor takes a FileStream object with Encoding, and buffer size as optional parameters. The following code snippet creates a StreamWriter from a FileStream with default encoding and buffer size.
  1. // Create a FileStream with mode CreateNew  
  2. FileStream stream = new FileStream(fileName, FileMode.CreateNew);  
  3. // Create a StreamWriter from FileStream  
  4. using (StreamWriter writer = new StreamWriter(stream))  
  5. {  
  6.    writer.Write("Hello StreamWriter");  
  7. }  
The following code snippet creates a StreamWriter from a FileStream with Encoding. Encoding supported are ASCII, Unicode, UTF32, UTF7, and UTF8. Encoding is defined in the System.Text namespace.
  1. using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF32))  
The following code snippet creates a StreamWriter from a FileStream with encoding and buffer size.
  1. using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF32, 512))  

StreamWriter.Write() method

 
StreamWriter.Write() method writes a char, string of chars, or a string to the steam. The following code snippet creates and writes different content to the stream.
  1. using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8 ))  
  2. {  
  3.    // Write a char  
  4.    writer.Write('y');  
  5.    // Write a char[]  
  6.    char[] arr = { '1''3''5''7' };  
  7.    writer.Write(arr);  
  8.    string author = "Mahesh Chand";  
  9.    // Write a string  
  10.    writer.Write(author);  
  11. }  

StreamWriter.WriteLine() method

 
StreamWriter.WriteLine() method writes a string to the next line to the steam. The following code snippet creates and writes different author names to the stream.
  1. using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8 ))  
  2. {  
  3.    writer.WriteLine("C# Corner Authors");  
  4.    writer.WriteLine("==================");  
  5.    writer.WriteLine("Monica Rathbun");  
  6.    writer.WriteLine("Vidya Agarwal");  
  7.    writer.WriteLine("Mahesh Chand");  
  8.    writer.WriteLine("Vijay Anand");  
  9.    writer.WriteLine("Jignesh Trivedi");  
  10. }  

StreamWriter.WriteAsync() method

 
StreamWriter.WriteAsync() method writes a char, string of chars, or a string to the stream asynchronously. The method returns a Task that represents the asynchronous write operation. The following code snippet creates and writes different content to the stream.
  1. static async void WriteCharacters()  
  2. {  
  3.    UnicodeEncoding encoder = new UnicodeEncoding();  
  4.    string str = "This is a StreamWriter code sample.";  
  5.    char[] chars = encoder.GetChars(  
  6.    encoder.GetBytes(str));  
  7.    using (StreamWriter writer = File.CreateText(@"C:\Temp\AsyncFile.txt"))  
  8.    {  
  9.       await writer.WriteAsync(chars, 0, chars.Length);  
  10.    }  
  11. }

StreamWriter.WriteLineAsync() method

 
StreamWriter.WriteLineAsync() method writes a char or char array to a new asynchronously. The method returns a Task that represents the asynchronous write operation. The following code snippet creates and writes a new line for each char to the stream.
  1. UnicodeEncoding encoder = new UnicodeEncoding();  
  2. using (StreamWriter writer = File.CreateText(@"C:\Temp\AsyncFile.txt"))  
  3. {  
  4.    await writer.WriteLineAsync('m');  
  5.    await writer.WriteLineAsync('a');  
  6.    await writer.WriteLineAsync('h');  
  7.    await writer.WriteLineAsync('e');  
  8.    await writer.WriteLineAsync('s');  
  9.    await writer.WriteLineAsync('h');  
  10. }  

StreamWriter Code Example

 
Here is the complete code example of the use of StreamWriter and its methods. The code also reads the content of the file and displays on the console.
  1. using System;  
  2. using System.IO;  
  3. using System.Text;  
  4. class Program  
  5. {  
  6.    static void Main(string[] args)  
  7.    {  
  8.       // File name  
  9.       string fileName = @"C:\Temp\CSharpAuthors.txt";  
  10.       FileStream stream = null;  
  11.       try  
  12.       {  
  13.          // Create a FileStream with mode CreateNew  
  14.          stream = new FileStream(fileName, FileMode.OpenOrCreate);  
  15.          // Create a StreamWriter from FileStream  
  16.          using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8 ))  
  17.          {  
  18.             writer.WriteLine("C# Corner Authors");  
  19.             writer.WriteLine("==================");  
  20.             writer.WriteLine("Monica Rathbun");  
  21.             writer.WriteLine("Vidya Agarwal");  
  22.             writer.WriteLine("Mahesh Chand");  
  23.             writer.WriteLine("Vijay Anand");  
  24.             writer.WriteLine("Jignesh Trivedi");  
  25.          }  
  26.       }  
  27. finally  
  28.    {  
  29.       if (stream != null)  
  30.       stream.Dispose();  
  31.    }  
  32.    // Read a file  
  33.    string readText = File.ReadAllText(fileName);  
  34.    Console.WriteLine(readText);  
  35.    Console.ReadKey();  
  36.    }  
  37. }
The output of the above code looks like the following,
 
CSharp StreamWriter example
 

Summary

 
In this article and code sample, we saw how to use a StreamWriter class to write to a text file.