C Sharp Stream Reader

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# StreamReader

C# StreamReader class is used to read string from the stream. It inherits TextReader class. It provides Read() and ReadLine() methods to read data from the stream.

C# StreamReader example to read one line

Let's see the simple example of StreamReader class that reads a single line of data from the file.

 
  1. using System;  
  2. using System.IO;  
  3. public class StreamReaderExample  
  4. {  
  5.     public static void Main(string[] args)  
  6.     {  
  7.         FileStream f = new FileStream("e:output.txt", FileMode.OpenOrCreate);  
  8.         StreamReader s = new StreamReader(f);  
  9.   
  10.         string line=s.ReadLine();  
  11.         Console.WriteLine(line);  
  12.   
  13.         s.Close();  
  14.         f.Close();  
  15.     }  
  16. }  

Output:

Hello C#

C# StreamReader example to read all lines

 
  1. using System;  
  2. using System.IO;  
  3. public class StreamReaderExample  
  4. {  
  5.     public static void Main(string[] args)  
  6.     {  
  7.         FileStream f = new FileStream("e:a.txt", FileMode.OpenOrCreate);  
  8.         StreamReader s = new StreamReader(f);  
  9.   
  10.         string line = "";  
  11.         while ((line = s.ReadLine()) != null)  
  12.         {  
  13.             Console.WriteLine(line);  
  14.         }  
  15.         s.Close();  
  16.         f.Close();  
  17.     }  
  18. }  

Output:

Hello C#
this is file handling