withTempPath<T> function

T withTempPath<T>(
  1. T callback(
    1. String path
    ), {
  2. String? prefix,
  3. String? suffix,
  4. String? parent,
})

Generates a unique temporary path name, passes it to callback, and deletes it after callback finishes.

This doesn't actually create anything at the path in question. It just chooses a name that's extremely unlikely to conflict with an existing entity, and deletes whatever's at that name after callback finishes.

The callback may return a Future, in which case the path isn't deleted until that Future completes. Whether or not callback returns a Future, this deletes the temporary path synchronously; use withTempPathAsync to delete it asynchronously instead.

If prefix is passed, it's addded to the beginning of the temporary path's basename. If suffix is passed, it's added to the end. If parent is passed, it's used as the parent directory for the path; it defaults to Directory.systemTemp.

Implementation

T withTempPath<T>(T callback(String path),
    {String? prefix, String? suffix, String? parent}) {
  var path = _tempPathName(prefix, suffix, parent);
  return tryFinally(() => callback(path), () {
    try {
      File(path).deleteSync(recursive: true);
    } on IOException {
      // Ignore cleanup errors. This is probably because the file was never
      // created in the first place.
    }
  });
}