Using a Temporary File in Your Application

Using a Temporary File in Your Application


You need a temporary file in which to store information. This file will exist only as long as the process that created it remains running.


Use the static GetTempPath and GetTempFileName methods on the Path class. To create the temporary file in the directory set as the temporary directory and get the full path to it, use the following line of code:

	string tempFilePathWithFileName = Path.GetTempFileName( );

Before the application terminates, you should delete this temporary file. The following line of code deletes this file:


The GetTempFileName method creates the temporary file and returns the path, including the name of the file and its extension. To create and obtain just the path without the filename, use the following line of code:

	string tempFilePathWithoutFileName = Path.GetTempPath( );


You should use a temporary file whenever you need to store information temporarily for later retrieval. The one thing you must remember is to delete this temporary file before the application that created it is terminated. If it is not deleted, it will remain in the user's temporary directory until the user manually deletes it.

The Path class provides two methods for working with temporary files. The first is the static GetTempPath method, which returns the path to the temporary directory. The temporary directory is found by searching the TMP, then the TEMP, then the USERPROFILE environment variables, and finally the Windows directory.

The second static method, GetTempFileName, will automatically generate a temporary filename, create a zero-length file in the user's temporary directory, and return a string containing this filename and its path.

See Also

See the "Directory Class," "File Class," and "Path Class" topics in the MSDN documentation.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows