Start Coding

Topics

C# StreamReader and StreamWriter

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: Reading Text Files

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.

Basic Usage of StreamReader


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: Writing to Text Files

StreamWriter allows you to write characters to a stream, typically a file. It's ideal for creating or appending text to files.

Basic Usage of StreamWriter


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.

Important Considerations

  • Always use the using statement or manually call Dispose() to ensure proper resource management.
  • StreamReader and StreamWriter work with text files. For binary files, consider using File I/O Operations or other specialized classes.
  • Be mindful of file permissions when reading from or writing to files.
  • For large files, consider reading or writing in chunks to optimize memory usage.

Advanced Features

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.

Error Handling

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.

Conclusion

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#.