How to Use StreamReader in C# to Read Text Files
Use
StreamReader in C# to read text from files by creating an instance with a file path and calling methods like ReadLine() or ReadToEnd(). Always wrap it in a using block to ensure the file is closed properly after reading.Syntax
The basic syntax to use StreamReader involves creating an instance with a file path and reading text using methods like ReadLine() or ReadToEnd(). Wrapping it in a using block ensures the file is closed automatically.
using: Ensures proper disposal of the reader.StreamReader(string path): Opens the file at the given path.ReadLine(): Reads one line at a time.ReadToEnd(): Reads the entire file content.
csharp
using System.IO; using (StreamReader reader = new StreamReader("file.txt")) { string line = reader.ReadLine(); string allText = reader.ReadToEnd(); }
Example
This example shows how to read a text file line by line using StreamReader and print each line to the console.
csharp
using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // Create a sample file to read File.WriteAllText(filePath, "Hello\nWorld\nStreamReader Example"); using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
Output
Hello
World
StreamReader Example
Common Pitfalls
Common mistakes when using StreamReader include not closing the file, which can lock it, and trying to read after the end of the file. Always use a using block or call Dispose() to close the reader. Also, avoid mixing ReadLine() and ReadToEnd() calls without resetting the position.
csharp
using System.IO; // Wrong way: Not closing the StreamReader StreamReader reader = new StreamReader("file.txt"); string content = reader.ReadToEnd(); // Forgot to call reader.Close() or Dispose() // Right way: Using 'using' block using (StreamReader reader2 = new StreamReader("file.txt")) { string content2 = reader2.ReadToEnd(); }
Quick Reference
Here is a quick summary of key StreamReader methods and tips:
| Method/Property | Description |
|---|---|
| StreamReader(string path) | Creates a reader for the specified file path. |
| ReadLine() | Reads the next line from the file. |
| ReadToEnd() | Reads all remaining text from the file. |
| Peek() | Returns the next character without reading it. |
| Close() / Dispose() | Closes the reader and releases resources. |
| using statement | Automatically closes the reader when done. |
Key Takeaways
Always use a using block with StreamReader to ensure the file is closed properly.
Use ReadLine() to read files line by line and ReadToEnd() to read the whole file at once.
Avoid reading after the end of the file to prevent errors.
StreamReader reads text files efficiently and is part of System.IO namespace.
Remember to handle exceptions for file not found or access errors.