Temporary files

suggest change

Programs often need a place to put data for a short time: an intermediate result of a conversion, a downloaded file before it's verified, a generated script to run, a scratch buffer too big for memory, test fixtures. That data should go into a temporary file or directory with a unique name, and it should be deleted when it's no longer needed.

dart:io gives you two building blocks:

There is no File.createTemp. The usual pattern is to create a temp directory and put files in it, and this article shows how to create a unique temp file when you really need one.

This article covers:

The examples were run with Dart 3.13 on Windows, and on Linux (WSL) where the behavior differs.

The system temp directory

Directory.systemTemp returns the temp directory of the current user. createTempSync creates a new directory inside it:

import 'dart:io';

void main() {
  final tmp = Directory.systemTemp;
  print('system temp: ${tmp.path}');
  print('exists: ${tmp.existsSync()}');

  final dir = Directory.systemTemp.createTempSync('myapp_');
  print('created:     ${dir.path}');

  final file = File('${dir.path}${Platform.pathSeparator}data.txt');
  file.writeAsStringSync('hello');
  print('file:        ${file.path} (${file.lengthSync()} bytes)');

  dir.deleteSync(recursive: true);
  print('deleted:     ${!dir.existsSync()}');
}

Output on Windows:

system temp: C:\Users\kjk\AppData\Local\Temp
exists: true
created:     C:\Users\kjk\AppData\Local\Temp\myapp_da2c3ed2
file:        C:\Users\kjk\AppData\Local\Temp\myapp_da2c3ed2\data.txt (5 bytes)
deleted:     true

Output on Linux:

system temp: /tmp
exists: true
created:     /tmp/myapp_PSEBAK
file:        /tmp/myapp_PSEBAK/data.txt (5 bytes)
deleted:     true

Where the directory is comes from the environment:

So you redirect temp files of a Dart program (for example to a bigger disk, or a RAM disk) by setting the variable before starting it:

$ TMPDIR=/home/kjk/tmp/scratch dart run temp.dart
system temp: /home/kjk/tmp/scratch
exists: true
created:     /home/kjk/tmp/scratch/myapp_UADPSC
file:        /home/kjk/tmp/scratch/myapp_UADPSC/data.txt (5 bytes)
deleted:     true

Use Directory.systemTemp rather than reading these variables yourself; it already handles the platform differences. See Environment variables.

Dart accepts / as a path separator on Windows too, so the rest of the examples use '${dir.path}/name'. For portable path handling (joining, getting the base name or extension) use package:path.

Creating temp directories

createTemp (async) and createTempSync take an optional prefix and append a random suffix. They can be called on any Directory, not only systemTemp:

import 'dart:io';

Future<void> main() async {
  final a = await Directory.systemTemp.createTemp('report_');
  final b = await Directory.systemTemp.createTemp('report_');
  final c = await Directory.systemTemp.createTemp();
  print(a.path);
  print(b.path);
  print(c.path);

  // createTemp works on any directory, not only the system one.
  final nested = await a.createTemp('part_');
  print(nested.path);

  for (final d in [a, b, c]) {
    await d.delete(recursive: true);
  }
}

Output on Windows:

C:\Users\kjk\AppData\Local\Temp\report_b071d9e4
C:\Users\kjk\AppData\Local\Temp\report_88bae675
C:\Users\kjk\AppData\Local\Temp\586d2c5
C:\Users\kjk\AppData\Local\Temp\report_b071d9e4\part_7e1a686

Output on Linux:

/tmp/report_QQSZTN
/tmp/report_YJOSAI
/tmp/LTAXMN
/tmp/report_QQSZTN/part_VZRXYX

Things to know:

Creating a temp file

When you need just one file, the simplest correct approach is a temp directory with a fixed file name inside it: the directory guarantees uniqueness. If you need a file directly in some existing directory, generate a random name and create the file with exclusive: true, which fails if the file already exists:

import 'dart:io';
import 'dart:math';

final _random = Random.secure();
const _chars = 'abcdefghijklmnopqrstuvwxyz0123456789';

String _randomName(int length) =>
    List.generate(length, (_) => _chars[_random.nextInt(_chars.length)]).join();

/// Creates a new, empty file with a unique name in [parent]
/// (the system temp directory by default).
Future<File> createTempFile({
  String prefix = 'tmp',
  String suffix = '',
  Directory? parent,
}) async {
  final dir = parent ?? Directory.systemTemp;
  for (var attempt = 0; attempt < 10; attempt++) {
    final file = File('${dir.path}${Platform.pathSeparator}'
        '$prefix${_randomName(10)}$suffix');
    try {
      // exclusive: true fails if the file already exists, so two
      // processes can never end up with the same file.
      return await file.create(exclusive: true);
    } on PathExistsException {
      continue;
    }
  }
  throw FileSystemException('cannot create a unique file', dir.path);
}

Future<void> main() async {
  final file = await createTempFile(prefix: 'export_', suffix: '.csv');
  print(file.path);
  print('length: ${await file.length()}');

  await file.writeAsString('id,name\n1,ann\n');
  print(await file.readAsString());

  // exclusive: true refuses to reuse an existing name.
  try {
    await File(file.path).create(exclusive: true);
  } on PathExistsException catch (e) {
    print('${e.runtimeType}: ${e.message}');
  }

  await file.delete();
}

Output:

C:\Users\kjk\AppData\Local\Temp\export_hs8hyos9nm.csv
length: 0
id,name
1,ann

PathExistsException: Cannot create file

Two details make this safe:

The suffix matters when the file is handed to a tool that looks at the extension, like an image converter or a spreadsheet program.

Deleting temp data reliably

Temp data must be deleted on every exit path, including exceptions. That's what try/finally is for (see try, finally, and cleanup). If you create temp directories in several places, wrap the pattern in a helper:

import 'dart:io';

/// Runs [body] with a fresh temporary directory and deletes the
/// directory afterwards, whether [body] succeeds or throws.
Future<T> withTempDir<T>(
  Future<T> Function(Directory dir) body, {
  String prefix = 'tmp_',
}) async {
  final dir = await Directory.systemTemp.createTemp(prefix);
  try {
    return await body(dir);
  } finally {
    try {
      await dir.delete(recursive: true);
    } on FileSystemException catch (e) {
      // Don't let a cleanup failure hide the result or the real error.
      stderr.writeln('warning: could not delete ${dir.path}: ${e.message}');
    }
  }
}

Future<void> main() async {
  late Directory seen;

  final total = await withTempDir((dir) async {
    seen = dir;
    for (var i = 1; i <= 3; i++) {
      await File('${dir.path}/part$i.txt').writeAsString('x' * i * 100);
    }
    var sum = 0;
    await for (final entity in dir.list()) {
      sum += await (entity as File).length();
    }
    return sum;
  }, prefix: 'sum_');
  print('total bytes: $total');
  print('${seen.path} exists: ${await seen.exists()}');

  try {
    await withTempDir((dir) async {
      seen = dir;
      await File('${dir.path}/half.txt').writeAsString('partial');
      throw StateError('conversion failed');
    });
  } on StateError catch (e) {
    print('caught: ${e.message}');
  }
  print('${seen.path} exists: ${await seen.exists()}');
}

Output:

total bytes: 600
C:\Users\kjk\AppData\Local\Temp\sum_e4b9d221 exists: false
caught: conversion failed
C:\Users\kjk\AppData\Local\Temp\tmp_8996aa56 exists: false

Notes on the helper:

Be careful with recursive: true on paths you didn't create. A bug that makes dir point at the wrong place deletes that place. Only delete directories returned by createTemp, never paths built from user input or configuration.

Windows: open files can't be deleted

On Windows a file that is open, in your process or any other, can't be deleted, and neither can the directory containing it:

import 'dart:io';

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('locked_');
  final file = File('${dir.path}/log.txt');
  final raf = await file.open(mode: FileMode.write);
  await raf.writeString('still open');

  try {
    await dir.delete(recursive: true);
    print('deleted while open');
  } on FileSystemException catch (e) {
    print('delete failed: ${e.message}');
    print('os error: ${e.osError?.message} (${e.osError?.errorCode})');
  }

  await raf.close();
  if (await dir.exists()) await dir.delete(recursive: true);
  print('deleted after close: ${!await dir.exists()}');
}

Output on Windows:

delete failed: Deletion failed
os error: The process cannot access the file because it is being used by another process (32)
deleted after close: true

Output on Linux:

deleted while open
deleted after close: true

Code that works fine on Linux and macOS can fail on Windows only, so:

Unnamed scratch files on Linux and macOS

The flip side of the POSIX behavior is a useful trick: delete a temp file right after opening it. The name disappears immediately, but the data stays accessible through the open handle until it's closed. Nothing is left behind even if the process crashes or is killed:

import 'dart:io';
import 'dart:typed_data';

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('scratch_');
  final file = File('${dir.path}/buffer.bin');
  final raf = await file.open(mode: FileMode.write); // read and write
  try {
    if (!Platform.isWindows) {
      // POSIX: the name disappears now, the data lives until close().
      await file.delete();
      print('name still exists: ${await file.exists()}');
    }

    for (var i = 0; i < 4; i++) {
      await raf.writeFrom(Uint8List(256 * 1024)..fillRange(0, 4, i + 1));
    }
    print('written: ${await raf.length()} bytes');

    await raf.setPosition(2 * 256 * 1024);
    final chunk = await raf.read(4);
    print('chunk 3 starts with: $chunk');
  } finally {
    await raf.close();
    await dir.delete(recursive: true);
  }
}

Output on Linux:

name still exists: false
written: 1048576 bytes
chunk 3 starts with: [3, 3, 3, 3]

On Windows the file keeps its name until the finally block deletes the directory. FileMode.write opens the file for both reading and writing (truncating it first), which is what you want for a scratch buffer you write and then read back with setPosition.

Permissions on Linux and macOS

C's mkdtemp, used by most languages, creates temp directories that only the owner can access. Dart's createTemp doesn't: it creates them with the default permissions, which with the usual umask of 022 means other users can list the directory and read the files in it:

import 'dart:io';

void main() {
  print('system temp: ${Directory.systemTemp.path}');
  final dir = Directory.systemTemp.createTempSync('myapp_');
  print('created:     ${dir.path}');
  print('mode:        ${dir.statSync().modeString()}');

  final file = File('${dir.path}/data.txt')..writeAsStringSync('hello');
  print('file mode:   ${file.statSync().modeString()}');
  dir.deleteSync(recursive: true);
}

Output on Linux:

system temp: /tmp
created:     /tmp/myapp_GQHBBM
mode:        rwxr-xr-x
file mode:   rw-r--r--

On a single-user machine, or on macOS where TMPDIR is already per-user, this rarely matters. On a shared Linux server where /tmp is shared by all users, don't put secrets (decrypted files, tokens, private keys, customer data) in such a directory. dart:io has no API for changing permissions, so call chmod:

import 'dart:io';

/// Creates a temp directory that only the current user can access.
Future<Directory> createPrivateTemp(String prefix) async {
  final dir = await Directory.systemTemp.createTemp(prefix);
  if (!Platform.isWindows) {
    final result = await Process.run('chmod', ['700', dir.path]);
    if (result.exitCode != 0) {
      await dir.delete();
      throw FileSystemException('chmod failed: ${result.stderr}', dir.path);
    }
  }
  return dir;
}

Future<void> main() async {
  final dir = await createPrivateTemp('secrets_');
  print('${dir.path}: ${(await dir.stat()).modeString()}');
  await dir.delete();
}

Output on Linux:

/tmp/secrets_SWRDWS: rwx------

The directory is empty when its permissions are changed, so no file is ever exposed. On Windows, the per-user temp directory is already accessible only by its owner and administrators, and modeString() doesn't reflect Windows ACLs.

Atomic writes: temp file plus rename

Writing a file in place is not atomic. If the program crashes halfway, or another process reads the file while it's being written, it sees a truncated file. A classic way to break a configuration file or a cache.

The fix: write the new contents to a temp file, then rename it over the target. A rename within one file system is atomic, so readers see either the complete old file or the complete new one:

import 'dart:io';
import 'dart:math';

/// Replaces the contents of [target] so that readers see either the old
/// or the new contents, never a partially written file.
Future<void> writeAtomic(File target, String contents) async {
  // The temp file must be in the same directory: rename is only atomic
  // within one file system, and the system temp dir may be on another.
  final suffix = Random().nextInt(1 << 32).toRadixString(16);
  final tmp = File('${target.path}.$suffix.tmp');
  try {
    await tmp.writeAsString(contents, flush: true);
    await tmp.rename(target.path); // replaces target if it exists
  } catch (_) {
    if (await tmp.exists()) await tmp.delete();
    rethrow;
  }
}

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('atomic_');
  final config = File('${dir.path}/config.json');
  try {
    await writeAtomic(config, '{"version": 1}');
    print(await config.readAsString());

    await writeAtomic(config, '{"version": 2}');
    print(await config.readAsString());

    print(await dir.list().map((e) => e.uri.pathSegments.last).toList());
  } finally {
    await dir.delete(recursive: true);
  }
}

Output:

{"version": 1}
{"version": 2}
[config.json]

Why each part is there:

The same pattern works for downloads: stream the response into name.part, verify the size or checksum, and only then rename it to name. See File uploads for the server-side version.

Passing temp files to other processes

A common use of temp files is giving data to another program: a generated script, a config file for a tool, a long list of arguments that wouldn't fit on a command line. Here a program generates a Dart script and runs it:

import 'dart:io';

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('gen_');
  try {
    final script = File('${dir.path}/generated.dart');
    await script.writeAsString('''
void main(List<String> args) {
  final n = int.parse(args.first);
  print('squares: \${[for (var i = 1; i <= n; i++) i * i]}');
}
''');

    // Platform.resolvedExecutable is the running `dart` binary.
    final result = await Process.run(
      Platform.resolvedExecutable,
      [script.path, '5'],
    );
    stdout.write(result.stdout);
  } finally {
    await dir.delete(recursive: true);
  }
}

Output:

squares: [1, 4, 9, 16, 25]

Process.run waits for the child to exit, so by the time finally runs, nothing holds the files open. With Process.start, wait for exitCode before deleting, otherwise the delete fails on Windows, or the child may not find its input on POSIX. See Running OS commands.

Cleaning up on Ctrl+C

finally blocks don't run when the process is stopped by a signal. Press Ctrl+C during a long job and its temp directory stays on disk forever. To handle that, watch SIGINT (and SIGTERM, which isn't supported on Windows) and clean up in the handler:

import 'dart:async';
import 'dart:io';

Future<void> main() async {
  final dir = await Directory.systemTemp.createTemp('job_');
  print('working in ${dir.path}');

  Future<void> cleanup() async {
    if (await dir.exists()) {
      await dir.delete(recursive: true);
      print('removed ${dir.path}');
    }
  }

  // Ctrl+C (SIGINT) and SIGTERM end the process without running
  // finally blocks, so delete the directory from the signal handler.
  final signals = [
    ProcessSignal.sigint,
    if (!Platform.isWindows) ProcessSignal.sigterm,
  ];
  final subs = [
    for (final signal in signals)
      signal.watch().listen((s) async {
        print('got $s');
        await cleanup();
        exit(130);
      }),
  ];

  try {
    for (var i = 1; i <= 10; i++) {
      await File('${dir.path}/chunk$i.bin').writeAsBytes(List.filled(1024, i));
      print('wrote chunk $i');
      await Future.delayed(const Duration(milliseconds: 300));
    }
  } finally {
    for (final sub in subs) {
      await sub.cancel();
    }
    await cleanup();
  }
}

Output on Linux, with SIGINT sent after about a second:

working in /tmp/job_LPULAK
wrote chunk 1
wrote chunk 2
wrote chunk 3
wrote chunk 4
got SIGINT
removed /tmp/job_LPULAK

The process exited with code 130. If the job finishes normally, the finally block cancels the signal subscriptions (otherwise they would keep the program running) and deletes the directory. Exit code 130 (128 + signal number 2) is the shell convention for "terminated by Ctrl+C". For a full treatment of signal handling see Signals and graceful shutdown.

No handler runs when the process is killed with SIGKILL, crashes in native code, or the machine loses power. For that you need the next technique.

Removing stale temp directories

A program that runs often (a CLI tool, a cron job, a server that restarts) can clean up after its own crashed runs at startup: delete directories with its prefix that haven't been touched for a while:

import 'dart:io';

/// Deletes directories in the system temp dir whose name starts with
/// [prefix] and that haven't been modified for [maxAge].
Future<int> deleteStaleTempDirs(String prefix, Duration maxAge) async {
  final cutoff = DateTime.now().subtract(maxAge);
  var deleted = 0;
  await for (final entity in Directory.systemTemp.list()) {
    if (entity is! Directory) continue;
    final name = entity.uri.pathSegments.lastWhere((s) => s.isNotEmpty);
    if (!name.startsWith(prefix)) continue;
    try {
      final modified = (await entity.stat()).modified;
      if (modified.isAfter(cutoff)) continue;
      await entity.delete(recursive: true);
      print('deleted $name');
      deleted++;
    } on FileSystemException catch (e) {
      // Another process may still be using it, or it's already gone.
      print('skipped $name: ${e.osError?.message ?? e.message}');
    }
  }
  return deleted;
}

Future<void> main() async {
  final old = await Directory.systemTemp.createTemp('cleanup_demo_');
  await Future.delayed(const Duration(seconds: 2));
  final fresh = await Directory.systemTemp.createTemp('cleanup_demo_');
  print('old:   ${old.path}');
  print('fresh: ${fresh.path}');

  final n = await deleteStaleTempDirs('cleanup_demo_', const Duration(seconds: 1));
  print('deleted $n, old exists: ${await old.exists()}, '
      'fresh exists: ${await fresh.exists()}');
  await fresh.delete();
}

Output:

old:   C:\Users\kjk\AppData\Local\Temp\cleanup_demo_73383d95
fresh: C:\Users\kjk\AppData\Local\Temp\cleanup_demo_b7756c04
deleted cleanup_demo_73383d95
deleted 1, old exists: false, fresh exists: true

In a real program maxAge would be hours or days, longer than any run can take, so a directory that another running instance is still using is never deleted. The prefix should be specific (mytool_, not tmp) so you never delete other programs' files. A directory's modification time changes only when entries are added, removed or renamed in it, not when a file inside is rewritten; if a job keeps rewriting the same file for hours, use a larger maxAge or check the files' times too.

Temp directories in tests

Tests that touch the file system should each get a fresh directory, so they don't interfere with each other or with files on the developer's machine. With package:test, create it in setUp and delete it in tearDown:

# pubspec.yaml
name: tproj
environment:
  sdk: ^3.13.0
dev_dependencies:
  test: ^1.33.0
// lib/tproj.dart
import 'dart:io';

/// Appends [line] to the log file in [dir], creating it if needed.
Future<void> appendLog(Directory dir, String line) async {
  await File('${dir.path}/app.log')
      .writeAsString('$line\n', mode: FileMode.append);
}
// test/log_test.dart
import 'dart:io';

import 'package:test/test.dart';
import 'package:tproj/tproj.dart';

void main() {
  late Directory dir;

  setUp(() async {
    dir = await Directory.systemTemp.createTemp('log_test_');
  });

  tearDown(() async {
    await dir.delete(recursive: true);
  });

  test('creates the log file', () async {
    await appendLog(dir, 'started');
    expect(await File('${dir.path}/app.log').readAsString(), 'started\n');
  });

  test('appends to an existing file', () async {
    await appendLog(dir, 'one');
    await appendLog(dir, 'two');
    expect(await File('${dir.path}/app.log').readAsLines(), ['one', 'two']);
  });

  test('addTearDown keeps setup and cleanup together', () async {
    final other = await Directory.systemTemp.createTemp('other_');
    addTearDown(() => other.delete(recursive: true));

    await appendLog(other, 'x');
    expect(await other.list().length, 1);
  });
}

Output of dart test:

00:00 +0: loading test/log_test.dart
00:00 +0: test/log_test.dart: creates the log file
00:00 +1: test/log_test.dart: appends to an existing file
00:00 +2: test/log_test.dart: addTearDown keeps setup and cleanup together
00:00 +3: All tests passed!

tearDown and addTearDown callbacks run even when the test fails, so failing tests don't leave directories behind. addTearDown registers cleanup right next to the code that created the resource, which is handy when only some tests need a temp directory. More testing patterns are in Parameterized tests and Testing in CI.

Redirecting systemTemp with IOOverrides

Sometimes the code under test calls Directory.systemTemp itself, and you want its temp files to land somewhere you control, for example to check what it wrote or to make sure it cleaned up. IOOverrides from dart:io replaces dart:io behavior for code running inside a zone:

import 'dart:io';

/// Library code that uses the system temp directory.
Future<Directory> makeScratch() =>
    Directory.systemTemp.createTemp('scratch_');

final class TempDirOverride extends IOOverrides {
  TempDirOverride(this.root);
  final Directory root;

  @override
  Directory getSystemTempDirectory() => root;
}

Future<void> main() async {
  final sandbox = await Directory.systemTemp.createTemp('sandbox_');
  try {
    final scratch = await IOOverrides.runWithIOOverrides(
      makeScratch,
      TempDirOverride(sandbox),
    );
    print('sandbox: ${sandbox.path}');
    print('scratch: ${scratch.path}');

    // Outside the zone, systemTemp is the real one again.
    print('outside: ${Directory.systemTemp.path}');
  } finally {
    await sandbox.delete(recursive: true);
  }
}

Output:

sandbox: C:\Users\kjk\AppData\Local\Temp\sandbox_8f21f6e
scratch: C:\Users\kjk\AppData\Local\Temp\sandbox_8f21f6e\scratch_6bd29878
outside: C:\Users\kjk\AppData\Local\Temp

IOOverrides is a base class, so the subclass must be marked base, final or sealed. Only the methods you override change; everything else behaves normally. The override applies to code running in the zone, including async continuations, but not to other isolates or child processes. For those, set TMPDIR or TMP in the environment argument of Process.start.

Summary

Task How
System temp directory Directory.systemTemp (TMPDIR on POSIX, TMP/TEMP on Windows)
New temp directory await Directory.systemTemp.createTemp('myapp_')
New temp file temp dir + fixed name, or random name + create(exclusive: true)
Delete it await dir.delete(recursive: true) in finally
Reusable cleanup withTempDir((dir) async { ... }) helper
Delete fails on Windows close all handles and wait for child processes first
Private directory on Linux/macOS chmod 700 right after createTemp
Atomic file replacement write target.xxx.tmp in the same dir with flush: true, then rename
Clean up on Ctrl+C ProcessSignal.sigint.watch() handler
Leftovers from crashed runs delete prefixed dirs older than a cutoff at startup
Tests setUp/tearDown or addTearDown
Redirect systemTemp IOOverrides.runWithIOOverrides with getSystemTempDirectory

Feedback about page:

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



Table Of Contents