File I/O in C#

Read, write, stream. Work with files safely without leaking handles.

60-Second Version: Use File class for quick reads/writes. Use StreamReader/StreamWriter for big files. Always dispose. Think of Kunal reading a pizza recipe book.

1. Quick & Easy: File Class

Small files? One-liners. Kunal reads today's menu.

string text = File.ReadAllText("menu.txt"); // Whole file
string[] lines = File.ReadAllLines("menu.txt"); // Array of lines
File.WriteAllText("receipt.txt", "Order #123 paid"); // Overwrite

2. Big Files: Stream It

5GB log file? Don't load all to RAM. Read line by line. Prerna processes customer data without crashing her laptop.

using var reader = new StreamReader("biglog.txt");
string line;
while ((line = reader.ReadLine())!= null) {
    Process(line); // One line at a time
} // using auto-closes file

3. Paths: Use Path.Combine

Never hardcode \ or /. Different OS, different slash.

string path = Path.Combine("orders", "2025", "jan.txt");
// Windows: orders\2025\jan.txt
// Linux: orders/2025/jan.txt
Beginner Trap: Kaushal forgets using. File stays locked. Next write throws "file in use". Fix: Always using var writer = new StreamWriter(path). It calls Dispose which closes the file.

Quick Check ๐Ÿง 

Comments on File I/O (0)

No comments yet. Be the first to share your thoughts!