Paths and safe file access
Paths and safe file access
File access starts with choosing a location and deciding who may control it. A path is a name, not permission to read or write. In this lesson, every real file belongs to a newly created temporary directory; no existing user files are used.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. File examples require an authorized disposable environment with a writable temporary directory and no concurrent writers.
Build a path from trusted components
Path.Combine joins components using platform conventions. Relative paths depend on the working directory unless an explicit base is supplied. A rooted later component can replace the earlier components. Never treat combining strings as an authorization check.
using System;using System.IO;string path = Path.Combine("inventory", "stock.json");Console.WriteLine(Path.GetFileName(path));Console.WriteLine(Path.GetExtension(path));The filename and extension are independent of the platform directory separator.
Expected output (reasoned, not executed):
stock.json.jsonMap a known identifier to a filename
A small allowlist is preferable to accepting arbitrary paths when there are only a few known documents. Resolve the identifier first; pass only the trusted filename to the filesystem.
using System;using System.IO;string? Resolve(string id) => id switch{ "stock" => "stock.json", "orders" => "orders.json", _ => null};foreach (string id in new[] { "stock", "other" }){ string? name = Resolve(id); Console.WriteLine(name is null ? "Rejected" : Path.GetFileName(name));}No supplied identifier becomes a filesystem path directly.
Expected output (reasoned, not executed):
stock.jsonRejectedCreate and remove a private lab fixture
Directory.CreateTempSubdirectory creates a fresh empty directory under the temporary directory. File.WriteAllText creates or replaces a file; File.ReadAllText reads the complete text. Use finally to clean up known lab-owned files even if reading fails.
using System;using System.IO;var folder = Directory.CreateTempSubdirectory("bytemind-");string path = Path.Combine(folder.FullName, "note.txt");try{ File.WriteAllText(path, "Stock: 4"); Console.WriteLine(File.ReadAllText(path)); Console.WriteLine(new FileInfo(path).Length);}finally{ File.Delete(path); folder.Delete();}The eight ASCII bytes need no byte order mark with the default UTF-8 WriteAllText overload. Cleanup only targets the known file and empty lab directory.
Expected output (reasoned, not executed):
Stock: 48Common mistakes and edge cases
GetFullPath normalizes path syntax, but does not establish that the resolved filesystem object is contained in a trusted root. Symlinks, reparse points, concurrent replacement and permissions matter. Do not rely on a string prefix or File.Exists as an authorization guarantee. File.Exists can also return false when access fails or a path is invalid; false is not reliable proof that a file is absent. Treat actual open/read failures according to the operation contract rather than assuming a prior existence check remains current. The examples assume an isolated temporary directory with no concurrent writers. Cleanup itself may fail; production code must report that failure rather than erase unrelated files.
Practice and recap
Add a third allowed identifier, returns, mapped to returns.json. Predict how stock, returns and unknown are handled. Explain why unknown should never reach File.ReadAllText.
Hint: Extend the switch rather than concatenating an identifier.
Learning objective: Restrict a lab operation to an owned directory. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Paths and safe file access — knowledge check
Apply the lesson concepts to the following scenarios.
What does Path.Combine guarantee?
What happens to an unmapped identifier in example 2?
Why use a newly created lab directory?
What can File.WriteAllText do to an existing file?
Does GetFullPath prove a path cannot cross a symlink?