In this article, we will learn how to create a temp file in the Temp Folder in C#.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Is the Temp Folder

The main purpose of this location is to store information for a short time. For example, we can use it to store temporary files related to a calculation, a backup copy of a file being edited, etc. As the “temp folder” name suggests, files written here are considered transitory, and thus we should not count on them being available after our application exits. While some operating systems periodically clear the temp folder of older files, it is good practice to remove any temporary files we create to help preserve disk space.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

For our examples, we will be using the Windows operating system. By default, on Windows, the temp folder is located at  %userprofile%\AppData\Local\Temp, where %userprofile% is the system variable referencing the currently logged-in user. Because the temp folder location varies between operating systems and even between users, the output from our examples will differ slightly between systems but have no fear, the results are the same! 

How to Create a File in the Temp Folder

First, let’s begin with a helper method, which we will use to exercise the different temporary file creation techniques:

public static class TempFileCreator
{
    public static void CreateTempFile(string filePath)
    {
        using var sw = new StreamWriter(filePath);

        sw.Write("Hello from CodeMaze!");
    }
}

Here we define a static TempFileCreator class and add a CreateTempFile() method that writes a simple message to a specified file. We use the StreamWriter class to write the message as it provides a straightforward way to write file content.

Creating a Temp File Using the GetTempPath() Method

Now, let’s create a temporary file using Path.GetTempPath() and our CreateTempFile() method:

var tempFile = Path.Combine(Path.GetTempPath(),"text.txt");
Console.WriteLine($"Creating temp file: '{tempFile}'");
TempFileCreator.CreateTempFile(tempFile);

Path.GetTempPath() returns the path of the system-defined Temp folder. Then, using Path.Combine(), we join the temporary path with our filename  "text.txt". Finally, we call our CreateTempFile() method to create the file:

Creating temp file: 'C:\Users\CodeMaze\AppData\Local\Temp\text.txt'

Now let’s read the file to verify our operation was successful:

Console.WriteLine($"Reading temp file contents: '{tempFile}'");
var tempFileContent = File.ReadAllText(tempFile);
Console.WriteLine(tempFileContent);
File.Delete(tempFile);

Here we make a call to File.ReadAllText() to read in the file contents. It should also be noted that we are cleaning up after ourselves by calling File.Delete() to remove our temporary file:

Reading temp file contents: 'C:\Users\CodeMaze\AppData\Local\Temp\text.txt'
Hello from CodeMaze!

Creating a Temp File Using the GetTempFileName() Method

Now let’s take a look at the GetTempFileName() method. This method creates a uniquely named file in the system-defined Temp folder and returns the full path as a string.

The benefit of this method is its uniqueness guarantee. We can be sure the file did not exist before calling the method, and since it creates the file, we know that it now exists and we have sufficient permissions to access it.

Let’s see it in action:

tempFile = Path.GetTempFileName();
Console.WriteLine($"Temp file '{tempFile}' exists? {File.Exists(tempFile)}");
TempFileCreator.CreateTempFile(tempFile);

Here we call Path.GetTempFileName() to create a temporary file and immediately call File.Exists() to verify the file’s creation. Following that, we use our CreateTempFile() method to add our “Hello from CodeMaze” message:

Temp file 'C:\Users\CodeMaze\AppData\Local\Temp\tmptlagxa.tmp' exists? True

Now, let’s verify the file contents:

Console.WriteLine($"Reading temp file contents: '{tempFile}'");
tempFileContent = File.ReadAllText(tempFile);
Console.WriteLine(tempFileContent);
File.Delete(tempFile);

Once again we call File.ReadAllText() to read the file contents and call File.Delete() to remove our temporary file:

Hello from CodeMaze!

Creating a Temp File Using the GetFolderPath() Method

Now let’s move to a final option for defining a temporary file path. This time we’ll use the Environment.GetFolderPath() method in combination with a custom file name. This method returns the path to system-defined special folders. For a list of available values, be sure to check the Microsoft documentation for the Environment.SpecialFolder enum:

var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
tempFile = Path.Combine(appDataPath, "text.txt");
Console.WriteLine($"Creating temp file: '{tempFile}'");
TempFileCreator.CreateTempFile(tempFile);

First, using Environment.GetFolderPath(), we get the path to the ApplicationData folder. Then, using Path.Combine(), we create the full path for our “text.txt” file. Then lastly, we use our CreateTempFile() method to write some content:

Creating temp file: 'C:\Users\CodeMaze\AppData\Roaming\text.txt'

Now, let’s verify it:

Console.WriteLine($"Reading temp file contents: '{tempFile}'");
tempFileContent = File.ReadAllText(tempFile);
Console.WriteLine(tempFileContent);
File.Delete(tempFile);

Once again, we call File.ReadAllText() to read our file’s content and write it to the console. We also call File.Delete() to be sure we are cleaning up after ourselves:

Reading temp file contents: 'C:\Users\CodeMaze\AppData\Roaming\text.txt'
Hello from CodeMaze!

Conclusion

In this article, we learned about various ways to create temporary files. We examined some of the methods provided by System.IO.Path that aid us in creating temporary files.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!