C# - StreamReader Class (System.IO) with Examples

StreamReader class in C#: Here, we will learn how to read text from the file using methods of this class in C#?
Submitted by Ridhima Agarwal, on September 27, 2017 [Last updated : March 21, 2023]

What is StreamReader Class?

StreamReader class in C# is used to read string from the Stream.

It inherits TextReader class, that can read a sequential series of characters. The namespace that will be included in this is System.IO.TextReader.

The StreamReader initializes the new instance of the StreamReader class for the specified stream. It provides Read() and ReadLine() methods to read data from the stream.

Let's go through the following example to understand better:

Note: There is a file named "abc.txt" in the same folder and content of file is:

This is line 1 written in file.
This is line 2 written in file.
This is line 3 written in file.
This is line 4 written in file.
This is line 5 written in file.

Example 1: C# program to read single line from file

using System;
using System.IO;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      // create an object of the FileStream in which pass 
      // the path  of the  file from which 
      // you need read the content.
      FileStream F = new FileStream("abc.txt", FileMode.OpenOrCreate);
      
      // create the object of the StreamReader class 
      // and pass object of FileStream as parameter.
      StreamReader S = new StreamReader(F);
      
      // Read the content from the file
      String Line = S.ReadLine();
      
      // Print the content on the screen
      Console.WriteLine(Line);
      
      // Close the respective files
      S.Close();
      F.Close();
    }
  }
}

Output

This is line 1 written in file.

Example 2: C# program to read all lines from file

using System;
using System.IO;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      // create an object of the FileStream in which pass 
      // the path  of the  file from which 
      // you need read the content
      FileStream F = new FileStream("abc.txt", FileMode.OpenOrCreate);
      
      // create the object of the StreamReader class 
      // and pass object of FileStream as parameter.
      StreamReader S = new StreamReader(F);
      
      // code to read multiple lines
      String Line = " ";
      while ((Line = S.ReadLine()) != null) {
        Console.WriteLine(Line);
      }
      
      // Close the respective files
      S.Close();
      F.Close();
    }
  }
}

Output

This is line 1 written in file.
This is line 2 written in file.
This is line 3 written in file.
This is line 4 written in file.
This is line 5 written in file.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.