StreamReader class allows you to read text files very easily. Its implementation is very easy and it is most popular among the programmer. However, there are many 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.

As mentioned above point it is very easy to read text file using StreamReader Class. Belo 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.

Example:

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();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *