File I/O
Why Files Matter
Variables disappear when your program ends — they live in RAM, which gets wiped. Files are your program's long-term memory. They let you save data to disk so it survives restarts, crashes, and even power outages.
C# makes file operations surprisingly easy. The File class has simple one-liner methods for common tasks, and StreamReader/StreamWriter give you fine-grained control for bigger files.
All file operations live in the System.IO namespace (included by default in top-level statements).
Quick File Operations with the File Class
StreamReader & StreamWriter — For Bigger Files
The File.ReadAllText() method loads the entire file into memory at once. That's fine for small files, but what if your file is 2 GB? Your app would eat all the RAM and crash.
StreamReader and StreamWriter work like a garden hose instead of a bucket. Instead of dumping all the water (data) at once, they flow it through a stream, using an internal buffer one piece at a time. Much more memory-friendly.
The using statement is critical here — it automatically closes the file when you're done, even if an exception occurs. Think of it as a "please put this back when you're finished" note.
StreamReader, StreamWriter & using
Async File I/O — Don't Freeze Your App
File operations can be slow — especially on old hard drives or over networks. If you read a big file on the main thread, your app freezes while waiting. Nobody wants a frozen app.
Async methods (with async/await) let your program keep doing other things while the file is being read. All the File methods have async versions — just add Async to the method name and await the call.