๐ WAYPOINT LESSON
Path, File, Directory
โญ beginnerโณ 12 min read๐ Lesson 54 of 85
Path manipulates names, File/Directory manipulate reality โ and combining them badly is a classic bug.
Three static classes
Pathโ string surgery on file names:Combine,GetFileName,GetExtension. It touches no disk.Fileโ one-shot operations:WriteAllText,ReadAllText,AppendAllText,Exists,Delete.Directoryโ folders:CreateDirectory,GetFiles,Exists.
string path = Path.Combine("/tmp", "cj", "notes.txt");
Directory.CreateDirectory(Path.GetDirectoryName(path)); // /tmp/cj
File.WriteAllText(path, "hello\n");
string again = File.ReadAllText(path);
The rules that prevent bugs
Path.Combine("a", "/b") โ an absolute second argument replaces the first; that's defined behavior, not a bug, but it surprises people. And File.WriteAllText overwrites without asking: a save-one-line bug can destroy yesterday's data. Check File.Exists when history matters, and prefer AppendAllText for logs.