C Sharp StreamReader

C# StreamReader

To read a string from the stream, the C# StreamReader class is used which inherits the TextReader class. To read data from the stream, the Read() and ReadLine() methods are facilitated by the C# StreamReader class.

Example:

using System;  
using System.IO;  
public class Example  
{  
    public static void Main(string[] args)  
    {  
        FileStream fs = new FileStream("d:\\file.txt", FileMode.OpenOrCreate);  
        StreamReader sr = new StreamReader(fs);  
 
        string line = sr.ReadLine();  
        Console.WriteLine(line);  
 
        sr.Close();  
        fs.Close();  
    }  
}

Output:

Explanation:

In the above example, we are using the C# StreamReader to read a single line of data from a file.

Example:

using System;  
using System.IO;  
public class Example  
{  
    public static void Main(string[] args)  
    {  
        FileStream fs = new FileStream("d:\\file.txt", FileMode.OpenOrCreate);  
        StreamReader sr = new StreamReader(fs);  
 
        string line = "";  
        while ((line = sr.ReadLine()) != null)  
        {  
            Console.WriteLine(line);  
        }  
        sr.Close();  
        fs.Close();  
    }  
}

Output:

Explanation:

In the above example, we are using the C# StreamReader to read all the lines of data from a file.

Please follow and like us:
Content Protection by DMCA.com