File repository and recovery
File repository and recovery
A file repository is a small component that loads and saves application data. It should distinguish an absent file from damaged content and failed access. A safe save prepares and validates a candidate before replacing existing data; even then, crash durability and concurrent access need additional engineering.
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.
Distinguish missing and malformed data
A missing file can mean first use, but malformed JSON may represent damaged data. Do not silently replace a damaged file with an empty collection. Handle only the expected error types and let unexpected I/O failures reach the caller.
using System;using System.IO;using System.Text.Json;var folder = Directory.CreateTempSubdirectory("bytemind-");string path = Path.Combine(folder.FullName, "stock.json");try{ Console.WriteLine(Load(path)); File.WriteAllText(path, "["); Console.WriteLine(Load(path)); File.WriteAllText(path, "[2,4]"); Console.WriteLine(Load(path));}finally { File.Delete(path); folder.Delete(); }static string Load(string path){ try { var values = JsonSerializer.Deserialize<int[]>(File.ReadAllText(path)); return values is null ? "Invalid data" : $"Loaded {values.Length}"; } catch (FileNotFoundException) { return "Missing"; } catch (JsonException) { return "Malformed"; }}The first load catches an absent file; the second detects an invalid JSON array; the third counts two entries.
Expected output (reasoned, not executed):
MissingMalformedLoaded 2Validate before replacing
Write the candidate beside the destination, validate its contents, then move it over the old file only when accepted. This fixture has a single writer, a tiny bounded payload and a known directory. An overwrite move is not a universal transactional or crash-durable guarantee.
using System;using System.IO;using System.Linq;using System.Text.Json;var folder = Directory.CreateTempSubdirectory("bytemind-");string current = Path.Combine(folder.FullName, "stock.json");string candidate = Path.Combine(folder.FullName, "candidate.json");try{ File.WriteAllText(current, "[4]"); foreach (string data in new[] { "[-1]", "[6,2]" }) { File.WriteAllText(candidate, data); var values = JsonSerializer.Deserialize<int[]>(File.ReadAllText(candidate)); if (values is not null && values.All(x => x >= 0)) File.Move(candidate, current, overwrite: true); Console.WriteLine(File.ReadAllText(current)); }}finally { File.Delete(candidate); File.Delete(current); folder.Delete(); }The rejected candidate never replaces the current file. The valid candidate is moved over it. Failures during the real move require explicit recovery.
Expected output (reasoned, not executed):
[4][6,2]Enforce a bounded read
Checking size after ReadAllText is too late to prevent allocation. In a single-writer fixture, a known seekable file can be checked before decoding. In hostile or concurrent environments enforce a byte budget while reading as well.
using System;using System.IO;var folder = Directory.CreateTempSubdirectory("bytemind-");string path = Path.Combine(folder.FullName, "data.txt");try{ File.WriteAllText(path, "123456789"); using var stream = File.OpenRead(path); if (stream.Length > 8) Console.WriteLine("Too large"); else { using var reader = new StreamReader(stream); Console.WriteLine(reader.ReadToEnd()); }}finally { File.Delete(path); folder.Delete(); }Nine bytes exceed the lab limit of eight. Both the reader, if created, and the file stream are disposed before cleanup.
Expected output (reasoned, not executed):
Too largeCommon mistakes and edge cases
Do not catch every exception and return an empty array: permission failures, malformed input and a valid empty array have different meanings. Validate file and domain data, bound reads, and define recovery behavior. Production designs may require exclusive ownership, backups, durability guarantees and a database transaction instead of file replacement. Async file operations follow in the next chapter.
Practice and recap
For a current file [4], consider candidate [0,5], candidate [-2], and malformed candidate [. Specify the expected current state after each independent attempt and when to report errors.
Hint: Use a fresh starting file for each case. Parse before validating quantities.
Learning objective: Handle missing or malformed data explicitly. 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
File repository and recovery — knowledge check
Apply the lesson concepts to the following scenarios.
What should a loader do with malformed JSON?
When should a candidate replace existing data?
Does File.Move with overwrite guarantee crash durability on every filesystem?
Why reject large files before reading all text?
What should an unexpected access failure mean?