File Handling
Learn how to read from and write to files using the System.IO namespace in C#.
The System.IO Namespace
C#'s `System.IO` namespace provides everything needed to work with files and directories — from simple one-line helpers to fine-grained streaming APIs.
Writing to a File
using System.IO;
string path = "notes.txt";File.WriteAllText(path, "Hello, file system!");
// Append more contentFile.AppendAllText(path, "\nSecond line.");Reading from a File
string content = File.ReadAllText(path);Console.WriteLine(content);
// Or read line by lineforeach (string line in File.ReadAllLines(path)){ Console.WriteLine($"Line: {line}");}Output
Click Run to see what this code prints.
Handling File Errors
File operations can fail for many reasons — a missing file, no permissions, or another process holding it open — so always wrap them in exception handling.
try{ string content = File.ReadAllText("missing.txt");}catch (FileNotFoundException){ Console.WriteLine("That file doesn't exist.");}FAQs
File.ReadAllText loads the entire file into memory at once — simple, fine for small files. StreamReader reads incrementally, better for very large files.
Summary
- System.IO provides File and Directory helpers for common tasks.
- File.WriteAllText/ReadAllText handle simple whole-file operations.
- Always handle exceptions around file I/O — the file system is inherently unreliable.