C# – Get temp folder path and create a temp file

You can use Path.GetTempPath() to get the user’s temp folder path. Here’s an example:

using System.IO;

var tempFolderPath = Path.GetTempPath();

Console.WriteLine(tempFolderPath);
Code language: C# (cs)

I’m running this in Windows, so it outputs my temp folder path:

C:\Users\makolyte\AppData\Local\Temp\Code language: plaintext (plaintext)

Path.GetTempPath() gets the temp folder path by checking environment variables (TMP, TEMP, USERPROFILE). It falls back to returning the system temp folder.

Create a temp file

Once you have the temp folder path, you can combine it with a file name and create a file. Here’s an example:

using System.IO;

var tempFolderPath = Path.GetTempPath();
var filePath = Path.Combine(tempFolderPath, "a.txt");

File.WriteAllText(filePath, "hello world");
Code language: C# (cs)

If you don’t need a specific temp file name, there’s a shortcut: Path.GetTempFileName(). This creates a temp file with a unique name in the temp folder and returns the file path (which you can then use to update the existing file). Internally, it uses Path.GetTempPath() to find the temp folder. Here’s an example:

using System.IO;

var tempFilePath = Path.GetTempFileName();

File.WriteAllText(tempFilePath, "hello world");

Console.WriteLine($"{tempFilePath} exists? {File.Exists(tempFilePath)}");
Console.WriteLine($"Content: {File.ReadAllText(tempFilePath)}");
Code language: C# (cs)

This example outputs the following (notice the temp file’s name):

C:\Users\makolyte\AppData\Local\Temp\tmp1C1A.tmp exists? True
Content: hello world
Code language: plaintext (plaintext)

Leave a Comment