Temporary files

suggest change

Programs often need a file that exists only for a short time: an intermediate result too big for memory, a download that isn't finished yet, input for an external tool, a scratch directory for a build step or a test.

.NET gives you the pieces in System.IO:

The hard part isn't creating a temp file, it's making sure it gets deleted and that nobody else can mess with it. This article covers both.

Examples use C# 14 / .NET 10 and run as file-based programs (dotnet run app.cs).

The temp directory

string tempDir = Path.GetTempPath();
Console.WriteLine(tempDir);

string path = Path.GetTempFileName();
Console.WriteLine(path);
Console.WriteLine($"exists: {File.Exists(path)}, size: {new FileInfo(path).Length}");

File.WriteAllText(path, "hello");
Console.WriteLine(File.ReadAllText(path));

File.Delete(path);
Console.WriteLine($"exists: {File.Exists(path)}");
C:\Users\kjk\AppData\Local\Temp\
C:\Users\kjk\AppData\Local\Temp\tmpo01f5p.tmp
exists: True, size: 0
hello
exists: False

GetTempPath() always ends with a directory separator. Where it points depends on the OS:

GetTempFileName() creates a zero-length file, so the name is reserved and another call can't return the same one. You get no choice of the name or the extension: it's always tmpXXXXXX.tmp in the temp directory. Old .NET Framework used the Win32 GetTempFileName function, which only had 65,535 unique names and threw IOException once the temp directory filled up with leftovers. Modern .NET generates random names, so that limit is gone, but the leftovers are still your problem.

The important part: nothing deletes the file for you. Every GetTempFileName() must be paired with a File.Delete, typically in a finally block or a Dispose method. The OS may clean the temp directory on reboot (Linux with tmpfs or systemd-tmpfiles), or never (Windows only cleans it when the user runs Disk Cleanup or Storage Sense).

Choosing your own name

When you need a specific extension (some tools insist on .csv or .zip), build the name yourself with Path.GetRandomFileName() or a Guid:

// random name, no file is created
for (int i = 0; i < 3; i++)
    Console.WriteLine(Path.GetRandomFileName());

// build your own name with a meaningful extension
string path = Path.Combine(Path.GetTempPath(), $"report-{Guid.NewGuid():N}.csv");
Console.WriteLine(Path.GetFileName(path));

// FileMode.CreateNew fails if the file already exists,
// so we never overwrite someone else's file
using (var fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write))
using (var w = new StreamWriter(fs))
{
    w.WriteLine("id,name");
    w.WriteLine("1,apple");
}
Console.WriteLine(File.ReadAllText(path).Length);

try
{
    using var again = new FileStream(path, FileMode.CreateNew);
}
catch (IOException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}
File.Delete(path);
ww5amjhb.zdd
jcgtl0ya.pwv
4syk2tq5.wzi
report-17a9668b0d284c82ba9f43efeded4e54.csv
18
IOException: The file 'C:\Users\kjk\AppData\Local\Temp\report-17a9668b0d284c82ba9f43efeded4e54.csv' already exists.

GetRandomFileName() uses a cryptographically strong random generator and returns 8 characters, a dot and 3 characters (about 55 bits of randomness). It's a name, not a file: between generating it and creating the file, something else could create a file with that name. In practice a collision is very unlikely, but always create the file with FileMode.CreateNew. It's atomic: it either creates a new file or throws, and never opens an existing one. With FileMode.Create or File.WriteAllText you would silently overwrite (or, in a shared /tmp, follow a symlink planted by another user).

Don't build names from a timestamp, process ID or a counter. Two processes started at the same time, or the same program run twice, will collide.

Temporary directories

When a task produces several files, create one temp directory and put everything in it. Cleanup is then a single recursive delete.

DirectoryInfo dir = Directory.CreateTempSubdirectory("myapp-");
Console.WriteLine(dir.Name);
try
{
    File.WriteAllText(Path.Combine(dir.FullName, "input.txt"), "data");
    Directory.CreateDirectory(Path.Combine(dir.FullName, "out"));
    File.WriteAllText(Path.Combine(dir.FullName, "out", "result.txt"), "done");

    foreach (string f in Directory.EnumerateFiles(dir.FullName, "*", SearchOption.AllDirectories))
        Console.WriteLine(Path.GetRelativePath(dir.FullName, f));
}
finally
{
    dir.Delete(recursive: true);
}
Console.WriteLine($"exists: {Directory.Exists(dir.FullName)}");
myapp-2mavv4zs.ks3
input.txt
out\result.txt
exists: False

Directory.CreateTempSubdirectory(prefix) was added in .NET 7. It creates the directory atomically under GetTempPath(), retrying with a new random name on collision. The optional prefix makes leftovers easy to identify (and to clean up later, see below). On Unix the directory is created with mode 700, so other users can't list or modify its contents, which matters in a shared /tmp.

Inside your own temp directory you can use fixed names like input.txt, because nobody else is using that directory.

On older .NET, the equivalent is Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())), without the atomicity and permission guarantees.

Delete on close

FileOptions.DeleteOnClose asks the operating system to delete the file when the last handle to it is closed. This is the most reliable cleanup, because it works even when an exception skips your cleanup code:

string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

using (var fs = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite,
    FileShare.None, bufferSize: 4096, FileOptions.DeleteOnClose))
{
    byte[] data = "scratch data"u8.ToArray();
    fs.Write(data);
    Console.WriteLine($"exists while open: {File.Exists(path)}");

    fs.Position = 0;
    using var reader = new StreamReader(fs, leaveOpen: true);
    Console.WriteLine(reader.ReadToEnd());
}

Console.WriteLine($"exists after close: {File.Exists(path)}");
exists while open: True
scratch data
exists after close: False

This is the right tool for a scratch buffer that only your process reads and writes: spill a large sort to disk, buffer an upload before computing its hash, and so on.

The limitations:

A disposable temp file and directory

For files you need to pass around by path, wrap creation and deletion in an IDisposable class, so a using statement guarantees cleanup:

using System.Diagnostics;

string filePath;
using (var tmp = new TempFile(".json"))
{
    File.WriteAllText(tmp.Path, """{"x": 1}""");
    Console.WriteLine($"{Path.GetExtension(tmp.Path)} {File.ReadAllText(tmp.Path)}");
    Console.WriteLine($"exists: {File.Exists(tmp.Path)}");
    filePath = tmp.Path;
}
Console.WriteLine($"exists after Dispose: {File.Exists(filePath)}");

string dirPath;
using (var dir = new TempDirectory("build-"))
{
    File.WriteAllText(dir.Combine("a.txt"), "a");
    Directory.CreateDirectory(dir.Combine("sub"));
    File.WriteAllText(dir.Combine("sub", "b.txt"), "b");
    dirPath = dir.Path;
    Console.WriteLine(Directory.GetFiles(dir.Path, "*", SearchOption.AllDirectories).Length);
}
Console.WriteLine($"dir exists after Dispose: {Directory.Exists(dirPath)}");

sealed class TempFile : IDisposable
{
    public string Path { get; }

    public TempFile(string extension = ".tmp")
    {
        Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(),
            System.IO.Path.GetRandomFileName() + extension);
        // create it now so the name is reserved
        using var _ = new FileStream(Path, FileMode.CreateNew);
    }

    public void Dispose()
    {
        try { File.Delete(Path); }
        catch (IOException e) { Debug.WriteLine($"can't delete {Path}: {e.Message}"); }
        catch (UnauthorizedAccessException e) { Debug.WriteLine($"can't delete {Path}: {e.Message}"); }
    }
}

sealed class TempDirectory : IDisposable
{
    public string Path { get; }

    public TempDirectory(string prefix = "tmp-") =>
        Path = Directory.CreateTempSubdirectory(prefix).FullName;

    public string Combine(params string[] parts) =>
        System.IO.Path.Combine([Path, .. parts]);

    public void Dispose()
    {
        try { Directory.Delete(Path, recursive: true); }
        catch (DirectoryNotFoundException) { }
        catch (IOException e) { Debug.WriteLine($"can't delete {Path}: {e.Message}"); }
        catch (UnauthorizedAccessException e) { Debug.WriteLine($"can't delete {Path}: {e.Message}"); }
    }
}
.json {"x": 1}
exists: True
exists after Dispose: False
2
dir exists after Dispose: False

Notes on the design:

Make sure every stream you opened on the file is closed before Dispose runs. On Windows you can't delete a file that is open, as shown next.

Deleting a file that is still open

On Unix you can delete (unlink) an open file. The directory entry disappears, and the data lives until the last handle is closed. On Windows File.Delete fails if any handle is open without FileShare.Delete:

string path = Path.GetTempFileName();

using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
    try { File.Delete(path); }
    catch (IOException e) { Console.WriteLine($"IOException: {e.Message}"); }
}

using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite,
    FileShare.ReadWrite | FileShare.Delete))
{
    File.Delete(path);
    Console.WriteLine($"deleted while open, exists: {File.Exists(path)}");
    fs.Write([1, 2, 3]);
    Console.WriteLine($"still writable, length: {fs.Length}");
}
IOException: The process cannot access the file 'C:\Users\kjk\AppData\Local\Temp\tmpxdwel2.tmp' because it is being used by another process.
deleted while open, exists: False
still writable, length: 3

If you open temp files with FileShare.Delete, cleanup code can delete them even while some other part of the program still has them open, and the code behaves the same on Windows and Unix.

File permissions on Linux and macOS

/tmp is shared by every user on the machine, so a temp file readable by others leaks data. The .NET temp APIs create private files, but plain File.WriteAllText follows the umask, which is usually 022 (readable by everyone):

if (OperatingSystem.IsWindows()) return;

Console.WriteLine(Path.GetTempPath());

string f = Path.GetTempFileName();
Console.WriteLine($"{f} {File.GetUnixFileMode(f)}");

DirectoryInfo d = Directory.CreateTempSubdirectory("myapp-");
Console.WriteLine($"{d.FullName} {d.UnixFileMode}");

string own = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var opts = new FileStreamOptions
{
    Mode = FileMode.CreateNew,
    Access = FileAccess.Write,
    UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite,
};
using (var fs = new FileStream(own, opts)) { }
Console.WriteLine($"{own} {File.GetUnixFileMode(own)}");

string plain = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
File.WriteAllText(plain, "x");
Console.WriteLine($"{plain} {File.GetUnixFileMode(plain)}");

File.Delete(f); File.Delete(own); File.Delete(plain); d.Delete();

Output on Linux:

/tmp/
/tmp/tmp1Z6qiS.tmp UserWrite, UserRead
/tmp/myapp-ZhvgWn UserExecute, UserWrite, UserRead
/tmp/0kitstv0.lb0 UserWrite, UserRead
/tmp/nefmeyxh.0oy OtherRead, GroupRead, UserWrite, UserRead

Run with TMPDIR=/var/tmp/ and GetTempPath() returns /var/tmp/. That's handy when /tmp is a small RAM disk (tmpfs) and you're writing large files.

Atomic writes: temp file plus rename

A classic use of a temp file is saving a file without the risk of leaving it half-written. If the program crashes in the middle of File.WriteAllText(path, ...), the file is truncated or corrupt. Instead, write the new contents to a temp file and then rename it over the original. A rename within the same volume is atomic: readers see either the old file or the new one, never a mix.

string settings = Path.Combine(Directory.GetCurrentDirectory(), "settings.json");
WriteAllTextAtomic(settings, """{"theme": "dark"}""");
Console.WriteLine(File.ReadAllText(settings));
WriteAllTextAtomic(settings, """{"theme": "light"}""");
Console.WriteLine(File.ReadAllText(settings));

var leftovers = Directory.GetFiles(Directory.GetCurrentDirectory(), "settings.json.*.tmp");
Console.WriteLine($"leftover temp files: {leftovers.Length}");
File.Delete(settings);

static void WriteAllTextAtomic(string path, string contents)
{
    // the temp file must be in the same directory (same volume)
    // so that the final move is a rename, not a copy
    string tmp = $"{path}.{Path.GetRandomFileName()}.tmp";
    try
    {
        using (var fs = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write))
        using (var w = new StreamWriter(fs))
        {
            w.Write(contents);
            w.Flush();
            fs.Flush(flushToDisk: true);
        }
        File.Move(tmp, path, overwrite: true);
    }
    catch
    {
        File.Delete(tmp);
        throw;
    }
}
{"theme": "dark"}
{"theme": "light"}
leftover temp files: 0

The details that matter:

The same pattern works for downloads: download to name.partial, then rename when complete, so a half-downloaded file never looks finished. It's useful for configuration files that the app writes back.

Cleaning up leftovers

Even with careful code, temp files are left behind when the process crashes, is killed or the machine loses power. If your app creates many temp files, give them a common prefix or put them in your own subdirectory, and delete old ones at startup:

string root = Path.Combine(Path.GetTempPath(), "myapp");
Directory.CreateDirectory(root);

// simulate leftovers from earlier runs
for (int i = 0; i < 3; i++)
{
    string f = Path.Combine(root, $"old-{i}.tmp");
    File.WriteAllText(f, "x");
    File.SetLastWriteTimeUtc(f, DateTime.UtcNow.AddDays(-2));
}
File.WriteAllText(Path.Combine(root, "fresh.tmp"), "x");

int deleted = DeleteOldFiles(root, TimeSpan.FromDays(1));
Console.WriteLine($"deleted {deleted}");
foreach (var f in Directory.EnumerateFiles(root))
    Console.WriteLine(Path.GetFileName(f));
Directory.Delete(root, recursive: true);

static int DeleteOldFiles(string dir, TimeSpan maxAge)
{
    DateTime cutoff = DateTime.UtcNow - maxAge;
    int n = 0;
    foreach (FileInfo fi in new DirectoryInfo(dir).EnumerateFiles("*.tmp"))
    {
        if (fi.LastWriteTimeUtc >= cutoff) continue;
        try { fi.Delete(); n++; }
        catch (IOException) { }               // in use by another process
        catch (UnauthorizedAccessException) { }
    }
    return n;
}
deleted 3
fresh.tmp

Only delete files older than some threshold. Another instance of your program may be running right now and using the fresh ones. Ignore errors: a file that can't be deleted is probably still in use.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents