How to Read a File Using StreamReader in C#
By FoxLearn 2/7/2025 3:28:11 AM 134
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.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
How to secure ASP.NET Core with NWebSec
11/07/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024