C# StreamReader Class with Programming Example

In this chapter you will learn:
  • What is StreamReader Class?
  • How to read file using StreamReader Class?
  • Programming Examples and Code

What is StreamReader Class?

StreamReader class allows you to read text files easily. Its implementation is easy and it is widely popular among the programmer. However, there are dozens of way to read text file in C# file handling but StreamReader Class is more popular in list.

Important Points about StreamReader Class
  1. Implements a TextReader that reads characters from a byte stream in a particular encoding.
  2. StreamReader class uses UTF-8 Encoding by defaults.
  3. StreamReader class is designed for character input in a particular encoding.
  4. Use this class for reading standard text file.
  5. By default, it is not thread safe.

How to read file using StreamReader class?

As mentioned above it is very easy to read text file using StreamReader Class. Here I am going to write a program that does following thing:
  1. Write some data on text file using StreamWriter class and
  2. Read those data using StreamReader class.
 

Programming Examples and Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace StreamReader_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\csharpfile.txt";
            
            //Writer data to text file
            using (StreamWriter writer = new StreamWriter(file))
            {
                writer.WriteLine("This tutorial explains how to use StreamReader Class in C# Programming");
                writer.WriteLine("Good Luck!");
            }

            //Reading text file using StreamReader Class            
            using (StreamReader reader = new StreamReader(file))
            {
                Console.WriteLine(reader.ReadToEnd());
            }            
            Console.ReadKey();

        }
    }
}

Output:
This tutorial explains how to use StreamReader Class in C# Programming

Good Luck! _

Summary

In this chapter you learned StreamReader class with complete programming example. In the next chapter you will learn TextWriter Class in C#.

 

Share your thought