Mastering File I/O in C#: StreamReader, StreamWriter, BinaryReader, and BinaryWriter
When you work with file input and output in C#, it's important to know how to work with StreamReader, StreamWriter, BinaryReader, and BinaryWriter when working with text and binary data. This article will cover those classes, examples, and best practices so you can use them right.
1. StreamReader: Reading Text Files
The StreamReader class is intended for reading text files. It simplifies reading characters, lines, and an entire file content.
Major Features
Reads a text efficiently.
Handles encoding gracefully.
Suits operations of line-by-line reading or character-based reading.
Example
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine())!= null)
{
Console.WriteLine(line);
}
}
}
}
Best Practices
Always use using statements to ensure the file is closed after reading.Check file existence using File.Exists to avoid exceptions.
2. StreamWriter: Writing Text Files
The StreamWriter class is used to write text to files. It is simple yet powerful and allows you to append or overwrite text files.
Key Features
Writes text efficiently.
Supports appending mode.
Handles encoding options.
Example
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
using (StreamWriter writer = new StreamWriter(filePath, append: true))
{
writer.WriteLine("This is a new line of text.");
}
Console.WriteLine("Text written successfully!");
}
}
End.
Always flush or close the writer to ensure data integrity.
3. BinaryReader: Reading from a Binary file
Use the BinaryReader class to read binary information, such as images, audio files, or object serialization.
Key Features:
Reads basic data types (int, float, string).
Does sequential reading.
Example
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.bin";
using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
int number = reader.ReadInt32();
string message = reader.ReadString();
Console.WriteLine($"Number: {number}, Message: {message}");
}
}
}.
Always use BinaryReader with the same format it has been written with.
--------------------------------------------------
4. BinaryWriter: Writing Binary Data
The BinaryWriter class is used to write binary data in a very efficient way and makes it the perfect class for creating compact files.
Key Features
It writes the primitive types in their binary format.
It allows for sequential writing of data.
Example
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.bin";
using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
{
writer.Write(42); // Write an integer
writer.Write("Hello, binary world!"); // Write a string
}
Console.WriteLine("Binary data written successfully!");
}
}
End
Do not use StreamReader/StreamWriter with BinaryReader/BinaryWriter on the same stream.
Always make reading and writing methods compatible with each other.
Comparing Text vs. Binary Classes
Best Practices for File I/O in C#
1. Always Close Streams: Use using blocks to automatically manage resources.
2. Handle Exceptions: Use try-catch blocks to handle IOException and UnauthorizedAccessException.
3. Validate File Paths: Always validate file paths to avoid runtime errors.
4. Match Read/Write Operations: Make sure that BinaryReader reads match the format of BinaryWriter.
---------------------------------------------------
Conclusion
Mastery of StreamReader, StreamWriter, BinaryReader, and BinaryWriter lets you handle quite a lot of file operations very effectively. Whether you are processing text logs or handling binary data; classes learned in this section make for a good basis on file I/O in C#. Applying examples and best practices here will make you write cleaner, safer, and more effective code.