IC Improve Code Recipes

Recipe 10.2 · C#

Atomic File Writes

Problem

A job writes an output file. Another process, or a person, reads it while it is half written and gets a truncated file. Or the job crashes in the middle, and the old good file has already been overwritten with half a new one. Both happen most often with exactly the files that matter: extracts for downstream systems, configuration and state files.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
using (var writer = new StreamWriter(outputPath, false))
{
    foreach (var row in rows)
    {
        writer.WriteLine(Format(row));
    }
}

The file exists, with partial content, from the first line until the last. A reader polling the folder sees it immediately.

The improved recipe

Write to a temporary file in the same folder, flush it to disk, then rename it over the target. A rename within one volume is atomic: readers see either the old file or the complete new one, never a mixture.

C#
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Files;

public static class AtomicFile
{
    public static async Task WriteAsync(
        string path,
        Func<Stream, CancellationToken, Task> write,
        CancellationToken ct = default)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(path);
        ArgumentNullException.ThrowIfNull(write);

        string target = Path.GetFullPath(path);
        string folder = Path.GetDirectoryName(target)!;
        Directory.CreateDirectory(folder);
        string temp = Path.Combine(folder,
            $".{Path.GetFileName(target)}.{Guid.NewGuid():N}.tmp");

        try
        {
            var options = new FileStreamOptions
            {
                Mode = FileMode.CreateNew,
                Access = FileAccess.Write,
                Share = FileShare.None,
                Options = FileOptions.Asynchronous
            };
            await using (var stream = new FileStream(temp, options))
            {
                await write(stream, ct);
                await stream.FlushAsync(ct);
                stream.Flush(flushToDisk: true);
            }
            File.Move(temp, target, overwrite: true);
        }
        catch
        {
            File.Delete(temp);
            throw;
        }
    }

    public static Task WriteAllTextAsync(
        string path,
        string contents,
        Encoding? encoding = null,
        CancellationToken ct = default)
    {
        ArgumentNullException.ThrowIfNull(contents);
        var enc = encoding ?? new UTF8Encoding(false);
        return WriteAsync(path, async (stream, token) =>
        {
            await using var writer =
                new StreamWriter(stream, enc, leaveOpen: true);
            await writer.WriteAsync(contents.AsMemory(), token);
        }, ct);
    }
}

A usage snippet that streams rows straight into the temporary file:

C#
await AtomicFile.WriteAsync(@"D:\exports\customers.csv",
    async (stream, ct) =>
    {
        await using var writer = new StreamWriter(stream);
        await foreach (var row in repository.StreamAsync(ct))
        {
            await writer.WriteLineAsync(row.ToCsvLine());
        }
    }, ct);

How it works

The temporary file sits in the same folder as the target, so it is on the same volume, which is what makes the rename atomic. Its name starts with a dot and ends with .tmp, so watchers and pickup jobs can be told to ignore it (Recipe 10.3), and it includes a GUID so two writers never collide on the temp name.

FileMode.CreateNew fails if the temp file somehow exists, rather than appending to junk. After the caller's delegate finishes, the stream is flushed twice: FlushAsync pushes .NET's buffer to the operating system, and Flush(flushToDisk: true) asks the operating system to push its cache to the disk. Without the second step, a power cut shortly after the rename can leave a correctly named file full of zeros on some file systems.

File.Move with overwrite: true replaces the target in one operation, using MoveFileEx with replace on Windows and rename on Linux. If anything fails before that, the catch deletes the temp file and rethrows, and the old target is untouched. File.Delete does not throw when the file is already gone.

WriteAllTextAsync covers the common case and defaults to UTF-8 without a byte order mark. Chapter 11 explains when a downstream reader, usually Excel, needs the mark.

Variations and pitfalls

  • Keep a backup. File.Replace(temp, target, backupPath) swaps the files and keeps the previous version, which is useful for configuration files. It requires the target to exist already.
  • Readers must cooperate. Atomic writes stop readers seeing partial files. They do not stop a reader holding the old file open, which on Windows makes the move fail with a sharing violation. Retry briefly, as the watcher in the next recipe does.
  • Signal files. If a downstream system wants a .done file, write the data file atomically first, then the signal file.