C# StreamWriter Example

Introduction

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 the 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: Write 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.

Creating a StreamWriter using a Filename

StreamWriter constructor takes a file name or a FileStream object with Encoding and buffer size as optional parameters.

CSharp StreamWriter

The following code snippet creates a StreamWriter from a filename with default encoding and buffer size. 

// File name  
string fileName = @"C:\Temp\Mahesh.txt";  
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.

string fileName = @"C:\Temp\CSharpAuthors.txt";  
try  
   {  
   using (StreamWriter writer = new StreamWriter(fileName))  
      {  
      writer.Write("This file contains C# Corner Authors.");  
      }  
   }  
catch(Exception exp)  
   {  
      Console.Write(exp.Message);  
   }  

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.

// Create a FileStream with mode CreateNew  
FileStream stream = new FileStream(fileName, FileMode.CreateNew);  
// Create a StreamWriter from FileStream  
using (StreamWriter writer = new StreamWriter(stream))  
{  
   writer.Write("Hello StreamWriter");  
}  

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.

using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF32))  

The following code snippet creates a StreamWriter from a FileStream with encoding and buffer size.

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.

using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8 ))  
{  
   // Write a char  
   writer.Write('y');  
   // Write a char[]  
   char[] arr = { '1', '3', '5', '7' };  
   writer.Write(arr);  
   string author = "Mahesh Chand";  
   // Write a string  
   writer.Write(author);  
}  

StreamWriter.WriteLine() method

StreamWriter.WriteLine() method writes a string to the next line of the steam. The following code snippet creates and writes different author names to the stream.

using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8 ))  
{  
   writer.WriteLine("C# Corner Authors");  
   writer.WriteLine("==================");  
   writer.WriteLine("Monica Rathbun");  
   writer.WriteLine("Vidya Agarwal");  
   writer.WriteLine("Mahesh Chand");  
   writer.WriteLine("Vijay Anand");  
   writer.WriteLine("Jignesh Trivedi");  
}  

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.

static async void WriteCharacters()  
{  
   UnicodeEncoding encoder = new UnicodeEncoding();  
   string str = "This is a StreamWriter code sample.";  
   char[] chars = encoder.GetChars(  
   encoder.GetBytes(str));  
   using (StreamWriter writer = File.CreateText(@"C:\Temp\AsyncFile.txt"))  
   {  
      await writer.WriteAsync(chars, 0, chars.Length);  
   }  
}

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.

UnicodeEncoding encoder = new UnicodeEncoding();  
using (StreamWriter writer = File.CreateText(@"C:\Temp\AsyncFile.txt"))  
{  
   await writer.WriteLineAsync('m');  
   await writer.WriteLineAsync('a');  
   await writer.WriteLineAsync('h');  
   await writer.WriteLineAsync('e');  
   await writer.WriteLineAsync('s');  
   await writer.WriteLineAsync('h');  
}

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 it on the console.

using System;  
using System.IO;  
using System.Text;  
class Program  
{  
   static void Main(string[] args)  
   {  
      // File name  
      string fileName = @"C:\Temp\CSharpAuthors.txt";  
      FileStream stream = null;  
      try  
      {  
         // Create a FileStream with mode CreateNew  
         stream = new FileStream(fileName, FileMode.OpenOrCreate);  
         // Create a StreamWriter from FileStream  
         using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8 ))  
         {  
            writer.WriteLine("C# Corner Authors");  
            writer.WriteLine("==================");  
            writer.WriteLine("Monica Rathbun");  
            writer.WriteLine("Vidya Agarwal");  
            writer.WriteLine("Mahesh Chand");  
            writer.WriteLine("Vijay Anand");  
            writer.WriteLine("Jignesh Trivedi");  
         }  
      }  
finally  
   {  
      if (stream != null)  
      stream.Dispose();  
   }  
   // Read a file  
   string readText = File.ReadAllText(fileName);  
   Console.WriteLine(readText);  
   Console.ReadKey();  
   }  
}

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 a text file.

Related Articles


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.