C# `StreamReader`: Efficiently Reading Character Data from Streams
Learn how to use C#'s `StreamReader` class to read character data from streams, including files. This tutorial demonstrates reading single lines and entire files, using the `Read()` and `ReadLine()` methods, and highlights the importance of using `using` statements for proper resource management and preventing resource leaks.
Using `StreamReader` in C# to Read from Streams
Introduction
The `StreamReader` class in C# is used to read character data from a stream. It's commonly used to read text from files, but it can work with any stream that provides character data. `StreamReader` inherits from `TextReader` and provides convenient methods like `Read()` and `ReadLine()`.
Reading a Single Line with `StreamReader`
This example shows how to open a file and read just one line using `StreamReader`.
Reading One Line
using System;
using System.IO;
public class StreamReaderExample {
public static void Main(string[] args) {
using (FileStream fileStream = new FileStream("e:\\output.txt", FileMode.OpenOrCreate)) { //Make sure file exists
using (StreamReader reader = new StreamReader(fileStream)) {
string line = reader.ReadLine();
Console.WriteLine(line); //Output the line read
}
}
}
}
Example Output (assuming "Hello C#" is in output.txt)
Hello C#
Reading All Lines with `StreamReader`
This example reads all lines from a file until the end of the file is reached.
Reading All Lines
using System;
using System.IO;
public class StreamReaderExample {
public static void Main(string[] args) {
using (FileStream fileStream = new FileStream("e:\\a.txt", FileMode.OpenOrCreate)) { //Make sure file exists
using (StreamReader reader = new StreamReader(fileStream)) {
string line;
while ((line = reader.ReadLine()) != null) {
Console.WriteLine(line);
}
}
}
}
}
Example Output (assuming "Hello C#" and "this is file handling" are in a.txt)
Hello C#
this is file handling
Important Note: Resource Management
The examples use a `using` statement. This ensures that the `FileStream` and `StreamReader` are properly closed, even if exceptions occur, preventing resource leaks.
Conclusion
The `StreamReader` class provides a convenient and efficient way to read text from streams in C#. Remember to use proper resource management techniques (like the `using` statement) to prevent resource leaks.