C# StreamReader

In c#, StreamReader is a class of System.IO namespace and it is useful to read characters from byte stream with a specific encoding. The StreamReader class has been derived from TextReader to provide the implementation of members to read a text from the stream and by default, it will use UTF8Encoding unless we specify other encodings.

 

Now, we will see how to use StreamReader class in c# to read a text from the file with examples.

C# StreamReader Example

Following is the example of reading text from a file using the StreamReader object in c#.

 

using System;

using System.IO;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            string fpath = @"D:\Test.txt";

            // Check if file exists

            if (File.Exists(fpath))

            {

                // creating StreamReader instance to read from a file

                using (StreamReader sr = new StreamReader(fpath))

                {

                    string txt;

                    // Read the data from file, until the end of file is reached                   

                    while ((txt = sr.ReadLine()) != null)

                    {

                        Console.WriteLine(txt);

                    }

                }

            }

            Console.ReadLine();

        }

    }

}

If you observe the above example, we imported a System.IO namespace in our example to access StreamReader object to open and read text from the given file.

 

When we execute the above example, it will read text from “Test.txt” file in D drive and return the result like as shown following.

 

C# StreamReader Example Result

 

This is how we can use StreamReader class in c# to read the data from a file in the file system.

 

PREVIOUS

C# StreamWriter
 

NEXT

C# BinaryWriter  
 

Topics Covered