How to Read a File Using StreamReader in C#
By Tan Lee Published on Feb 07, 2025 264
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
Freedash bootstrap lite
Nov 13, 2024
Material Lite Admin Template
Nov 14, 2024
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Material Dashboard Admin Template
Nov 17, 2024