How to Read a File Using StreamReader in C#
By Tan Lee Published on Feb 07, 2025 419
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 ofFileInfo
opens the file inFileMode.Open
(to open an existing file), withFileAccess.Read
(to allow reading), andFileShare.Read
(to allow other users to read the file while it's open). - A
StreamReader
is created to read the content of the file. TheReadToEnd()
method reads all the content from the file. - Finally, Close both the
StreamReader
andFileStream
to ensure the resources are properly released.
Categories
Popular Posts
Structured Data using FoxLearn.JsonLd
Jun 20, 2025
Implement security headers for an ASP.NET Core
Jun 24, 2025
What Are RESTful Web Services?
Feb 19, 2024
Plus Admin Dashboard Template
Nov 18, 2024