Understanding StreamWriter class - Coding Sharp

Understanding StreamWriter class

We have seen how to write in text file using File class in our previous article. Today we will see how to use StreamWriter class to write in a text file.
This class is very helpful to write text data into files. This class contains method to write to a file synchronously like Write and WriteLine or asynchronously WriteAsync and WriteLineAsync.
Using Statements. It is recommended to use using statements while we are using Stream Writer class, which ensures that is is removed from the memory once it is no longer needed. The syntax is very easy to use.
Lets check with the example that how to synchronously write to a text file using Stream Writer class. First we need to declare and initialize an instance of the class with using statement. It is available is available in System.IO namespace

Example 1

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writer = new StreamWriter(@"C:\Users\Tarun\Documents\File1.txt"))
        {
            writer.Write("First Word");
            writer.WriteLine("Second Word");
            writer.WriteLine("Third Line to write into the text file.");
            writer.Close();
            Console.ReadLine();
        }
    }
}

Example 2
Now lets check with the example that how to asynchronously write to a text file.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writerAsync = new StreamWriter(@"C:\Users\Tarun\Documents\AsyncFile1.txt"))
        {
            writerAsync.WriteAsync("First Word");
            writerAsync.WriteLineAsync("Second Word");
            writerAsync.WriteLineAsync("Third Line to write into the text file.");
            writerAsync.Close();
            Console.ReadLine();
        }

    }
}

See the below output for both example

StreamWriter class output
StreamWriter class output

Note : With the using statement and Stream Writer class we have written a text file. It is a excellent class and useful for many C# programmers.
Download the whole working code here.