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 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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Stisla Admin Dashboard Template
11/18/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024
Portal HTML Bootstrap
11/14/2024