File I/O, File, Directory, Path & Streams Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 26 of 35 ๐Ÿ“‚ Phase 9: Exceptions, Files & JSON ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: System.IO ยท File.ReadAllText ยท File.WriteAllText ยท Async File I/O ยท StreamReader ยท StreamWriter ยท Path ยท Directory ยท File Metadata

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.

1File Static Methods โ€” Read, Write & Append
C# โ€” File Read, Write & Append โ–ถ Run in Compiler
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);
2Async File Operations (Best Practice for Production)
C# โ€” Async File Read & Write โ–ถ Run in Compiler
// 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);
3StreamReader & StreamWriter (Large File Processing)

StreamReader and StreamWriter provide line-by-line and character-level stream processing, ideal for large files that shouldn't be loaded entirely into RAM.

C# โ€” StreamReader & StreamWriter โ–ถ Run in Compiler
// 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);
    }
}
4Path, Directory & File Operations
C# โ€” Path, Directory & File Class โ–ถ Run in Compiler
// 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.");
}
5Technical FAQs

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.