StreamReader Class in C# with Example

StreamReader Class in C# with Example
StreamReader Class in C# with Example

StreamReader class is basically used for reading text files.  StreamReader class resides in System.IO namespace.  If you want to make use of StreamReader class, then you must include System.IO namespace by making use of using keyword on top of your code.  StreamReader class got various methods like ReadLine(), ReadToEnd(), etc.

Upon creating an instance of StreamReader class, you can directly pass path of text file to the constructor, which you want to read.  Since the path of file contains some special characters like backslash(\), we make use of escape sequence by adding another backslash in front of it or you can use @ symbol in front of it to make the path verbatim literal.  Please click here for tutorial about Escape Sequence and Verbatim Literal in C#.

There is a method called Close() in the StreamReader class. You must invoke that method after you finished reading your text file to release any system resources associated with the reader.

using System;
using System.IO;

namespace Hello
{   

    class Program
    {
        static void Main(string[] args)
        {
            //Creating instance of streamreader.
            StreamReader _sr = new StreamReader(@"C:\Users\Admin\Desktop\mytext.txt");

            Console.WriteLine(_sr.ReadToEnd());

            _sr.Close();
        }
            
    }
}

Output:

Hi,

This tutorial is written by Fwait.com.  Keep browsing for more tutorials on this
site.

Thank You!

Press any key to continue . . .

This is another code example where you can read the text file line by line using StreamReader Class.

using System;
using System.IO;

namespace Hello
{   

    class Program
    {
        static void Main(string[] args)
        {
            //Creating instance of streamreader.
            StreamReader _sr = new StreamReader(@"C:\Users\Admin\Desktop\mytext.txt");

            string line;

            //Read until the ReadLine method return null value.
            while((line =_sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }

            _sr.Close();
        }
            
    }
}

 Output:

Hi,

This tutorial is written by Fwait.com.  Keep browsing for more tutorials on this
site.

Thank You!
Press any key to continue . . .