How to read file using StreamReader in C#?

0

 

How to read file using StreamReader in C#?

In C#, reading a file is a common task that is required in many software applications. The StreamReader class in C# provides an easy way to read text files line by line. In this blog, we will explore how to read a file using StreamReader in C#.

Understanding Reading a File using StreamReader in C#:

To read a file using StreamReader in C#, you first need to create an instance of the StreamReader class and pass the file path as an argument to the constructor. Here's an example:


using System.IO;
string filePath = "C:\\myFile.txt";
using (StreamReader reader = new StreamReader(filePath)) {
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}


In this example, we are creating an instance of the StreamReader class and passing the file path as an argument to the constructor. We are using the using statement to ensure that the StreamReader object is properly disposed of after it is used. The ReadLine() method is used to read each line of the file and print it to the console.

Using StreamReader with Different Encodings:

By default, StreamReader uses the UTF-8 encoding to read text files. However, if your text file uses a different encoding, you can specify the encoding when you create the StreamReader object. Here's an example:



using System.IO;
using System.Text;
string filePath = "C:\\myFile.txt";
using (StreamReader reader = new StreamReader(filePath, Encoding.GetEncoding("iso-8859-1")))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

In this example, we are using the Encoding.GetEncoding() method to specify the ISO-8859-1 encoding for the StreamReader object.

In this blog, we explored how to read a file using StreamReader in C#. We discussed creating an instance of the StreamReader class, passing the file path as an argument to the constructor, and using the ReadLine() method to read each line of the file. We also discussed how to specify different encodings for the StreamReader object. Reading files is an important task in many software applications, and by understanding how to use StreamReader in C#, you can make this task more efficient and reliable.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !