How to Read a File Using StreamReader in C#

By FoxLearn 2/7/2025 3:28:11 AM   84
To read a file in C#, you can use the StreamReader class. It simplifies reading text from a file by providing various methods for reading data.

The following example demonstrates how to read a file using StreamReader.

For example, Read a File Using StreamReader

// Create an object of FileInfo for the specified file path
FileInfo file = new FileInfo(@"C:\Example\MyFile.txt");

// Open the file in read-only mode
FileStream fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);

// Create an instance of StreamReader by passing the FileStream object
StreamReader reader = new StreamReader(fileStream);

// Read the entire content of the file using ReadToEnd method
string fileContent = reader.ReadToEnd();

// Close the StreamReader and FileStream objects to release resources
reader.Close();
fileStream.Close();

In this example:

  • The FileInfo class is used to define the path to the file.
  • The Open() method of FileInfo opens the file in FileMode.Open (to open an existing file), with FileAccess.Read (to allow reading), and FileShare.Read (to allow other users to read the file while it's open).
  • A StreamReader is created to read the content of the file. The ReadToEnd() method reads all the content from the file.
  • Finally, Close both the StreamReader and FileStream to ensure the resources are properly released.