Skip to content

Checkpoint: Saving Safely

The Course
•
30 min study

Saving seems simple until something goes wrong halfway. This checkpoint builds the two safeguards that the tracker relies on: a save that can't destroy the last good copy, and a load that changes nothing unless everything checks out.

The danger of a half-finished write

If a program stops during File.WriteAllText, the old contents are already gone and the new ones are only partly there. Writing to a temporary file and then moving it is much safer. A move within a folder is effectively all or nothing, so the real file is always a complete old or complete new version.

Replace in one step C#
Save("data.txt", "version 1");
Console.WriteLine(File.ReadAllText("data.txt"));

Save("data.txt", "version 2");
Console.WriteLine(File.ReadAllText("data.txt"));
Console.WriteLine(File.Exists("data.txt.tmp"));

static void Save(string path, string content)
{
    string temporary = path + ".tmp";
    File.WriteAllText(temporary, content);
    File.Move(temporary, path, overwrite: true);
}
Check your prediction
Text
version 1
version 2
False

Don't touch what you have until you're sure

Here is a load done two ways. Careless empties its list before it knows that the replacement is good. Careful builds the new data on the side, and swaps it in only when all of it is valid. Predict how many values each one has after a bad load.

Two ways to load C#
var careless = new List<int> { 1, 2 };
var careful = new List<int> { 1, 2 };

Careless(careless, new[] { "3", "bad" });
Careful(careful, new[] { "3", "bad" });

Console.WriteLine(careless.Count);
Console.WriteLine(careful.Count);

Careful(careful, new[] { "7", "8", "9" });
Console.WriteLine(careful.Count);

static void Careless(List<int> values, string[] input)
{
    values.Clear();
    foreach (string text in input)
    {
        if (!int.TryParse(text, out int value))
        {
            return;
        }
        values.Add(value);
    }
}

static void Careful(List<int> values, string[] input)
{
    var replacement = new List<int>();
    foreach (string text in input)
    {
        if (!int.TryParse(text, out int value))
        {
            return;
        }
        replacement.Add(value);
    }
    values.Clear();
    values.AddRange(replacement);
}
Check your prediction
Text
1
2
3

Fix it: The second save fails

Save writes to a temporary file and then moves it over the real one. The first save works. Run it.

The second save fails C#
Save("data.txt", "first");
Save("data.txt", "second");
Console.WriteLine(File.ReadAllText("data.txt"));

static void Save(string path, string text)
{
    string temp = path + ".tmp";
    File.WriteAllText(temp, text);
    File.Move(temp, path);
}
Check your prediction
Text
IOException

File.Move refuses to replace a file that already exists, so the pattern works only until there's something to protect, which is the whole point of it. Fix Save so the second call replaces the file.

Fix it

Pass overwrite: true, which replaces the old file in one step:

C#
Save("data.txt", "first");
Save("data.txt", "second");
Console.WriteLine(File.ReadAllText("data.txt"));

static void Save(string path, string text)
{
    string temp = path + ".tmp";
    File.WriteAllText(temp, text);
    File.Move(temp, path, overwrite: true);
}
Text
second

Deleting the old file first and then moving would also run, but for a moment there'd be no file at all, and a crash at that moment would lose everything. Replacing in one step keeps either the old file or the new one.

Build it yourself

Exercise

A safe contact book

Build a ContactBook class holding a list of Contact(string Name, string Email), with a public Contacts property and an Add method. Add these two methods, using the Result, Ok and Fail types from the workspace:

  • Save(string path) writes indented JSON through a temporary file, and returns Ok with the count.
  • Load(string path) returns Fail with a clear message if the file is missing, or if the JSON is invalid, or if any contact has a blank name or an email without @. On any failure, the contacts stay as they were.

Add two contacts, save, add a third, load (back to two), then try to load a file with an invalid email and another with broken JSON, and print the results and final count.

When it works, it prints the lines below. Each Name { … } line is a record's built-in ToString, so print the record itself rather than formatting it:

Text
Ok { Value = 2 }
Ok { Value = 2 }
2
Fail { Error = bad.json has an invalid contact }
Fail { Error = broken.json isn't valid JSON }
True
2
Your workspace C#
#nullable enable

using System.Text.Json;

Console.WriteLine(new Fail<int>("nothing yet"));

abstract record Result<T>;

sealed record Ok<T>(T Value) : Result<T>;

sealed record Fail<T>(string Error) : Result<T>;

record Contact(string Name, string Email);
Hint 1: the idea

Load has three stages: read, parse, validate. Only after all three succeed do you touch the list. Convert the exceptions from the first two stages into Fail.

Hint 2: a first step

Write Save and the good path of Load with no error handling. Then break the file on purpose and add a catch for each exception you see.

Show one solution
C#
#nullable enable

using System.Text.Json;

var book = new ContactBook();
book.Add(new Contact("Ana", "ana@example.com"));
book.Add(new Contact("Ben", "ben@example.com"));
Console.WriteLine(book.Save("contacts.json"));

book.Add(new Contact("Cy", "cy@example.com"));
Console.WriteLine(book.Load("contacts.json"));
Console.WriteLine(book.Contacts.Count);

File.WriteAllText("bad.json", "[{\"Name\":\"Di\",\"Email\":\"no-at-sign\"}]");
Console.WriteLine(book.Load("bad.json"));
File.WriteAllText("broken.json", "[{");
Console.WriteLine(book.Load("broken.json"));
Console.WriteLine(book.Load("missing.json") is Fail<int>);
Console.WriteLine(book.Contacts.Count);

class ContactBook
{
    private readonly List<Contact> contacts = new();

    public IReadOnlyList<Contact> Contacts => contacts;

    public void Add(Contact contact)
    {
        contacts.Add(contact);
    }

    public Result<int> Save(string path)
    {
        string temporary = path + ".tmp";
        File.WriteAllText(temporary, JsonSerializer.Serialize(contacts, new JsonSerializerOptions { WriteIndented = true }));
        File.Move(temporary, path, overwrite: true);
        return new Ok<int>(contacts.Count);
    }

    public Result<int> Load(string path)
    {
        List<Contact>? loaded;
        try
        {
            loaded = JsonSerializer.Deserialize<List<Contact>>(File.ReadAllText(path));
        }
        catch (IOException)
        {
            return new Fail<int>($"can't read {path}");
        }
        catch (JsonException)
        {
            return new Fail<int>($"{path} isn't valid JSON");
        }
        if (loaded is null || loaded.Any(contact => string.IsNullOrWhiteSpace(contact.Name) || contact.Email is null || !contact.Email.Contains('@')))
        {
            return new Fail<int>($"{path} has an invalid contact");
        }
        contacts.Clear();
        contacts.AddRange(loaded);
        return new Ok<int>(contacts.Count);
    }
}

abstract record Result<T>;

sealed record Ok<T>(T Value) : Result<T>;

sealed record Fail<T>(string Error) : Result<T>;

record Contact(string Name, string Email);
Text
Ok { Value = 2 }
Ok { Value = 2 }
2
Fail { Error = bad.json has an invalid contact }
Fail { Error = broken.json isn't valid JSON }
True
2

Save writes a temporary file and then replaces the real one in a single move, so a crash leaves either the old file or the new one, never half of each. Load reads into a local list and validates every contact before touching contacts. Only then does it clear and refill, which is why the failed loads at the end leave the book with its 2 contacts.

Was this article helpful?

Your response is saved on this device.