C# Reference ยท Files and I/O
Temporary files and directories in C#
Reference for temporary files in C#: Path.GetTempPath, GetTempFileName, GetRandomFileName, Directory.CreateTempSubdirectory and FileOptions.DeleteOnClose.
Programs often need a scratch place on disk: a download that is not finished yet, a file to hand to another tool, or a folder for a unit test. .NET gives you a few helpers for this in System.IO. Path.GetTempPath() returns the operating system's temporary folder, Path.GetTempFileName() creates an empty uniquely named file in it, and Directory.CreateTempSubdirectory() creates a private folder you can fill freely.
Temporary files are not deleted for you. Whoever creates one is responsible for removing it, normally in a finally block or through FileOptions.DeleteOnClose. If you forget, the file stays in the temp folder until the operating system or the user cleans it up.
string file = Path.GetTempFileName(); // empty file, already created DirectoryInfo dir = Directory.CreateTempSubdirectory("job-");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static string Path.GetTempPath(); public static string Path.GetTempFileName(); public static string Path.GetRandomFileName(); public static DirectoryInfo Directory.CreateTempSubdirectory(string? prefix = null); public static FileStream File.Create(string path, int bufferSize, FileOptions options);
| Member | Description |
|---|---|
Path.GetTempPath() |
The temp folder, always ending with a directory separator. On Linux and macOS it honors TMPDIR and defaults to /tmp/; on Windows it uses %TMP%/%TEMP%. |
Path.GetTempFileName() |
Creates a zero-byte file with a unique name and the extension .tmp and returns its full path. |
Path.GetRandomFileName() |
Returns a cryptographically strong random 12-character name such as a1b2c3d4.xyz. It does not touch the disk. |
Directory.CreateTempSubdirectory(prefix) |
Creates a new uniquely named folder inside the temp folder (since .NET 7) and returns a DirectoryInfo. The optional prefix starts the folder name. |
FileOptions.DeleteOnClose |
Passed to a FileStream constructor: the file is deleted when the stream is closed. |
Returns: paths as strings, or a DirectoryInfo for the folder helper.
Errors: IOException when no unique name can be found or the temp folder is full, UnauthorizedAccessException when the temp folder is not writable.
Usage notes
- You must clean up. Wrap the work in
try/finallyand callFile.DeleteorDirectory.Delete(path, true). Deleting a file that does not exist is not an error, so cleanup code can be unconditional. GetTempFileName()creates the file for you. That makes it safe against two programs picking the same name, but the extension is always.tmp. If you need another extension, create a name yourself withPath.ChangeExtensionon the result (and delete the original), or build a path inside a private temp subdirectory.- Prefer a private subdirectory for several files.
Directory.CreateTempSubdirectory()keeps your files together, and one recursive delete removes everything. In tests it avoids clashes between parallel runs. GetRandomFileName()is only a name. Another process could create a file with the same name before you do, so open the file withFileMode.CreateNewto fail instead of overwriting.- Do not print temp paths. They differ per machine and per run, which makes output and logs hard to compare.
- Security. The temp folder is shared. On multi-user systems never put secrets in a predictable name; random names and
CreateTempSubdirectory()(which restricts the folder to the current user on Unix) are the safe choices. - Large temp data. The temp folder can be a RAM disk (
/tmpoften is). For multi-gigabyte intermediate data check the free space or choose a configured work folder instead. DeleteOnCloseis handy for a scratch buffer that must not outlive the stream. While the stream is open the file exists on disk like any other, as the example shows.