C# File Handling and Streams Explained
C# provides powerful APIs for working with files, directories, and streams. Developers can use these features to create, read, write, copy, move, and delete files in desktop, web, and server applications.
What is File Handling in C#?
File handling allows an application to store and retrieve data from files on the operating system. The System.IO namespace contains many of the classes used for file and directory operations.
using System.IO;
Creating a File
The File class provides simple methods for creating and managing files.
string path = "data.txt";
File.WriteAllText(path, "Hello from C#");
Reading a File
ReadAllText reads the complete contents of a text file into a string.
string content = File.ReadAllText("data.txt");
Console.WriteLine(content);
Writing Text to a File
WriteAllText creates a file or replaces its existing contents with the supplied text.
File.WriteAllText("notes.txt", "C# File Handling\nLearning Streams");
Appending Data
AppendAllText adds text to the end of an existing file instead of replacing its contents.
File.AppendAllText("notes.txt", "\nNew line added.");
Checking Whether a File Exists
File.Exists can be used to check whether a specified file is available before attempting an operation.
if (File.Exists("data.txt"))
{
Console.WriteLine("File exists");
}
Copying, Moving, and Deleting Files
The File class also provides methods for common file management operations.
File.Copy("data.txt", "backup.txt", true);
File.Move("backup.txt", "archive.txt");
File.Delete("archive.txt");
Working with Directories
The Directory class is used to create, inspect, and remove directories.
Directory.CreateDirectory("Reports");
string[] files = Directory.GetFiles("Reports");
foreach (string file in files)
{
Console.WriteLine(file);
}
File Handling Command Table
| Method | Purpose | Example |
|---|---|---|
| WriteAllText | Write text to a file | File.WriteAllText(...) |
| ReadAllText | Read text from a file | File.ReadAllText(...) |
| AppendAllText | Append text | File.AppendAllText(...) |
| Copy | Copy a file | File.Copy(...) |
| Move | Move or rename a file | File.Move(...) |
| Delete | Delete a file | File.Delete(...) |
| Exists | Check file existence | File.Exists(...) |
Using StreamReader
StreamReader is useful for reading text from files incrementally instead of loading the entire file into memory at once.
using StreamReader reader = new StreamReader("data.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
Using StreamWriter
StreamWriter allows applications to write text to a stream, making it useful for creating logs and processing large amounts of text.
using StreamWriter writer = new StreamWriter("log.txt");
writer.WriteLine("Application started");
writer.WriteLine("Processing data...");
Using FileStream
FileStream provides lower-level access to file data as a stream of bytes. It can be useful when working with binary data or when more control over file I/O is required.
using FileStream stream = new FileStream(
"data.bin",
FileMode.Create,
FileAccess.Write
);
byte[] data = { 10, 20, 30, 40 };
stream.Write(data, 0, data.Length);
Synchronous vs Asynchronous File Operations
| Feature | Synchronous | Asynchronous |
|---|---|---|
| Execution | Waits for I/O to complete | Can await I/O completion |
| Example | File.ReadAllText | File.ReadAllTextAsync |
| Best For | Simple operations | Responsive and scalable applications |
Asynchronous File Reading
Modern .NET provides asynchronous file APIs that can be useful when applications perform file I/O without wanting to block while waiting for the operation to complete.
string content = await File.ReadAllTextAsync("data.txt");
Console.WriteLine(content);
Handling File Exceptions
File operations can fail because of missing files, invalid paths, permissions, locked files, or other operating system conditions. Applications should handle expected failures appropriately.
try
{
string content = File.ReadAllText("data.txt");
Console.WriteLine(content);
}
catch (FileNotFoundException)
{
Console.WriteLine("The file was not found.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access to the file was denied.");
}
Real-World Applications
- Application logging
- Configuration files
- Report generation
- CSV processing
- Document management
- Data import and export
- Local application storage
Common Mistakes to Avoid
- Using incorrect or hard-coded paths
- Ignoring file access permissions
- Loading very large files completely into memory
- Forgetting to dispose streams
- Overwriting important files accidentally
- Ignoring file operation exceptions
Advanced File Handling Concepts
- MemoryStream
- BufferedStream
- BinaryReader and BinaryWriter
- FileSystemWatcher
- Asynchronous streams
- Path manipulation
- File locking
Practice Exercises
- Create a text file
- Write and read user information
- Append application logs
- Copy a file to a backup directory
- List files from a directory
- Read a large file line by line
- Build a simple text-file based notes application
Conclusion
C# provides a complete set of tools for file and directory operations. The File, Directory, StreamReader, StreamWriter, and FileStream APIs allow developers to build applications that efficiently work with text and binary data.