IC Improve Code Recipes

Recipe 10.7 · C#

Temp Files That Clean Up After Themselves

Problem

Code creates temporary files for conversions, downloads and report generation, and forgets them. On one manufacturing client's report server, the temp folder held more than a million files and had silently pushed the system drive to its last few megabytes. Path.GetTempFileName adds its own trap: on Windows it fails once the temp folder holds 65,535 files with its naming pattern.

The way it's often written

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

C#
string tmp = Path.GetTempFileName();
File.WriteAllBytes(tmp, pdfBytes);
ConvertToTiff(tmp, output);
// tmp is never deleted

The improved recipe

Wrap temp files and folders in disposable types so using deletes them, put them under one application-specific folder, and sweep that folder for leftovers at startup.

C#
using System;
using System.IO;

namespace ImproveCode.Files;

public sealed class TempFile : IDisposable
{
    private static readonly string Root =
        Path.Combine(Path.GetTempPath(), "ImproveCode");

    private TempFile(string path) => FullPath = path;

    public string FullPath { get; }

    public static TempFile Create(string extension = ".tmp")
    {
        Directory.CreateDirectory(Root);
        string name = Path.GetRandomFileName();
        string path = Path.Combine(
            Root, Path.ChangeExtension(name, extension));
        using (new FileStream(path, FileMode.CreateNew))
        {
        }
        return new TempFile(path);
    }

    public static FileStream OpenScratchStream()
    {
        Directory.CreateDirectory(Root);
        string path = Path.Combine(
            Root, Path.GetRandomFileName());
        return new FileStream(path, FileMode.CreateNew,
            FileAccess.ReadWrite, FileShare.None, 81920,
            FileOptions.DeleteOnClose | FileOptions.Asynchronous);
    }

    public static int SweepOlderThan(TimeSpan age)
    {
        if (!Directory.Exists(Root))
        {
            return 0;
        }
        int deleted = 0;
        DateTime cutoff = DateTime.UtcNow - age;
        foreach (var info in new DirectoryInfo(Root)
                     .EnumerateFileSystemInfos())
        {
            if (info.LastWriteTimeUtc >= cutoff)
            {
                continue;
            }
            try
            {
                if (info is DirectoryInfo dir)
                {
                    dir.Delete(recursive: true);
                }
                else
                {
                    info.Delete();
                }
                deleted++;
            }
            catch (IOException)
            {
                // In use by a running job; the next sweep retries.
            }
        }
        return deleted;
    }

    public void Dispose()
    {
        try
        {
            File.Delete(FullPath);
        }
        catch (IOException)
        {
            // Still open elsewhere; SweepOlderThan removes it later.
        }
    }
}

public sealed class TempFolder : IDisposable
{
    private TempFolder(string path) => FullPath = path;

    public string FullPath { get; }

    public static TempFolder Create(string prefix = "ic-") =>
        new(Directory.CreateTempSubdirectory(prefix).FullName);

    public void Dispose()
    {
        try
        {
            Directory.Delete(FullPath, recursive: true);
        }
        catch (IOException)
        {
            // A file is still open; the OS temp cleanup handles it.
        }
    }
}

A usage snippet:

C#
TempFile.SweepOlderThan(TimeSpan.FromDays(1)); // at startup

using (var temp = TempFile.Create(".pdf"))
{
    await File.WriteAllBytesAsync(temp.FullPath, pdfBytes, ct);
    ConvertToTiff(temp.FullPath, outputPath);
} // deleted here, even if ConvertToTiff throws

await using (var scratch = TempFile.OpenScratchStream())
{
    await download.CopyToAsync(scratch, ct);
    scratch.Position = 0;
    await ImportAsync(scratch, ct);
} // the operating system deletes it on close

How it works

TempFile.Create uses Path.GetRandomFileName, which returns a random name without touching the disk, instead of Path.GetTempFileName, which creates a file and has the 65,535 limit on Windows. The file is created with FileMode.CreateNew so a name collision fails instead of handing two callers the same file. Dispose deletes it, so a using block covers every exit path, exceptions included.

OpenScratchStream is for data that never needs a path: a download staged before import, or a large intermediate result. FileOptions.DeleteOnClose asks the operating system to delete the file when the last handle closes. That includes the process being killed, which a finally block cannot handle.

All temp files live under one folder named after the application, so SweepOlderThan can safely delete anything older than a day without touching other programs' files. Call it at startup and, for long-running services, once a day from a scheduled job. The narrow catch (IOException) blocks are deliberate and commented: a file that is still in use will be removed by the next sweep, and cleanup should never crash the job that called it.

TempFolder uses Directory.CreateTempSubdirectory (.NET 7 and later), which creates a uniquely named folder in the system temp path. It is the right home for zip extraction (Recipe 10.4) or any job that produces several intermediate files.

Variations and pitfalls

  • Sensitive data. Temp files are plain files. For decrypted documents or exports with personal data, use a folder with restricted permissions, or keep the data in memory when it is small enough.

On .NET Framework

Directory.CreateTempSubdirectory and FileStreamOptions are not available. Build the folder name from Path.GetTempPath() and Path.GetRandomFileName() and create it with Directory.CreateDirectory. FileOptions.DeleteOnClose and the rest of the recipe work as shown.