File I/O, File, Directory, Path & Streams Masterclass
Welcome to Phase 9 (Chapter 26): C# File Handling, System.IO, StreamReader, StreamWriter & Async I/O Masterclass! The System.IO namespace provides comprehensive APIs for file, directory, and stream operations. In this chapter, we master reading and writing text files using File static methods, file metadata via FileInfo, directory navigation with Directory and Path, low-level streaming with StreamReader/StreamWriter, and async file operations using await.
using System.IO;
// 1. Write all text to file (creates or overwrites file)
File.WriteAllText("notes.txt", "Learning C# file handling in 2026!
Line 2.");
// 2. Read entire file content as string
string content = File.ReadAllText("notes.txt");
Console.WriteLine(content);
// 3. Append text to existing file without overwriting
File.AppendAllText("notes.txt", "
Appended new line.");
// 4. Read all lines as array of strings
string[] lines = File.ReadAllLines("notes.txt");
Console.WriteLine($"Total lines: {lines.Length}");
// 5. Write array of lines to file
string[] studentNames = { "Ravi Kumar", "Alice Johnson", "Bob Smith" };
File.WriteAllLines("students.txt", studentNames);
// Async File Write (Non-blocking โ recommended in ASP.NET Core)
await File.WriteAllTextAsync("notes.txt", "Learning C# file handling");
// Async File Read
string content = await File.ReadAllTextAsync("notes.txt");
Console.WriteLine(content);
StreamReader and StreamWriter provide line-by-line and character-level stream processing, ideal for large files that shouldn't be loaded entirely into RAM.
// Write using StreamWriter (using disposes automatically)
using (StreamWriter writer = new StreamWriter("report.txt"))
{
writer.WriteLine("=== MONTHLY REPORT ===");
writer.WriteLine($"Generated: {DateTime.Now:yyyy-MM-dd}");
writer.WriteLine("Total Sales: โน45,000");
}
// Read using StreamReader
using (StreamReader reader = new StreamReader("report.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
// Path operations (cross-platform safe!)
string filePath = Path.Combine("data", "users", "profile.json");
Console.WriteLine($"File Path: {filePath}");
Console.WriteLine($"Extension: {Path.GetExtension(filePath)}");
Console.WriteLine($"File Name: {Path.GetFileName(filePath)}");
Console.WriteLine($"Directory: {Path.GetDirectoryName(filePath)}");
// Directory creation
Directory.CreateDirectory("data/users");
// File existence check
if (File.Exists("notes.txt"))
{
File.Copy("notes.txt", "notes_backup.txt", overwrite: true);
Console.WriteLine("Backup created successfully.");
}
Q1: Why use async file methods in web applications?
Synchronous file I/O blocks the calling thread while waiting for disk operations, reducing ASP.NET Core server throughput. Async I/O releases the thread back to handle other requests during disk wait time.
Q2: What does the 'using' statement do with StreamReader/StreamWriter?
The using statement automatically calls Dispose() on the stream object when the block exits (even if an exception is thrown), flushing and releasing the file handle resource.