StreamReader and StreamWriter are powerful classes in C# that facilitate reading from and writing to text files. They provide efficient methods for handling file I/O operations, making them essential tools for developers working with file-based data.
StreamReader is used to read characters from a stream, typically a file. It's particularly useful when you need to read text files line by line or in chunks.
using System;
using System.IO;
string filePath = "example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
In this example, we open a file named "example.txt" and read its contents line by line. The using
statement ensures that the StreamReader is properly disposed of after use.
StreamWriter allows you to write characters to a stream, typically a file. It's ideal for creating or appending text to files.
using System;
using System.IO;
string filePath = "output.txt";
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, StreamWriter!");
writer.WriteLine("This is a new line.");
}
This code creates a new file named "output.txt" and writes two lines to it. If the file already exists, it will be overwritten by default.
using
statement or manually call Dispose()
to ensure proper resource management.Both StreamReader and StreamWriter offer additional methods for more specific operations:
Peek()
: Allows you to look at the next character without advancing the reader position.Read()
: Reads a single character from the stream.Write()
: Writes a string or character to the stream without adding a new line.Flush()
: Clears all buffers for the writer and causes any buffered data to be written to the underlying stream.When working with files, it's crucial to implement proper error handling. Use try-catch blocks to manage exceptions that may occur during file operations.
try
{
using (StreamReader reader = new StreamReader("nonexistent.txt"))
{
// Read file contents
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File not found: {ex.Message}");
}
catch (IOException ex)
{
Console.WriteLine($"An I/O error occurred: {ex.Message}");
}
This approach ensures that your application gracefully handles common file-related errors, enhancing its robustness and user experience.
StreamReader and StreamWriter are indispensable tools for C# developers working with text files. They provide efficient, easy-to-use methods for reading and writing operations. By understanding their usage and implementing proper error handling, you can create reliable and performant file I/O operations in your C# applications.
For more advanced file handling techniques, explore File and Directory Classes in C#.