How to read the contents of a text file using StreamReader class in C#?

Using StreamReader class in C# can be fun and very handy to do some important tasks. Here is an example which will help you to understand how to use the StreamReader to read through a text file and also write it to the console line by line.

In the sample code below an instance of StreamReader is created to read the text file. Please note the StreamReader is enclosed within the using statement so that the Stream is closed implicitly once the reading is done. 
Then the code loops through the StreamReader one line at a time using the ReadLine method, till it reaches the end of file and writes the content of the file to the console one line at a time.

 

using System;
using System.IO;
class MyTextReader
{
    public static void Main()
    {
        try
        {          
     // Use StreamReader within the using statement so that it closes  
     //the StreamReader once finished Reading. This is a good practice.
     using (StreamReader reader = new StreamReader("MyTestFile.txt"))
     {
         string line;

               //Read one line at a time and write it to the console till it
               //reaches the end of the file.
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            // Display Error Messages to the user.
            Console.WriteLine("Error Reading this File:");
            Console.WriteLine(e.Message);
        }
    }
}

 

Happy Coding.

Robert