C# Programming > Data

C# Temporary Files

Temporary Files

Working with temporary files in C# is simple and easy. The .NET Framework has classes to safely create temporary files.

Temporary files give C# developers the freedom to write information to the hard drive for whatever reason. There are very few things required to work with temporary files.

Temporary File Path

A temporary file is a file that an application uses for a temporary amount of time. Temporary files are generated by the application and are usually not essential for the application to run.

With that said, a temporary file can be created anywhere in the system. However Windows has a folder set aside specifically for temporary files. Creating temporary files within that folder is good practice.

Temporary file operations are built into the System.IO namespace. To get the location of the temporary path use the follow C# code (note that the path will include "\" at the end):

string windowsTempPath = Path.GetTempPath();

File Name

The problem with creating a temporary file inside the same folder as other applications is that file names might conflict. There are two easy ways around this problem.

The first is to use the following code to generate a completly random filename:

string randomFileName = Path.GetRandomFileName();

Chances of GetRandomFileName returning a filename that already exists are slim. Developers might still want to double check so there are not file conflicts.

The second way to avoid file name conflicts is to use the GetTempFileName function. This function make everything easy by not only generating a safe file name, but actually creating the temporary file inside Window's designated temp folder.

string tempFile = Path.GetTempFileName();
//The file now exists in the system

The second technique is definitely the easiest to use.

Conclusion

All that is left is to write and read the temporary file in C#. There are many uses for temporary files for .NET applications. The .NET Framework makes it as simple as possible. Under the Code Snippet section Markus wrote a very cool temporary file class that makes all this even easier.

Back to C# Article List