DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 11.18 Using a Temporary File in Your Application

Problem

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.

Solution

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:

File.Delete(tempFilePathWithFileName);

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( );

Once all files are closed, before the application terminates, this temporary directory should be deleted as well. The following line of code deletes this directory and any files or subdirectories within it:

Directory.Delete(tempFilePathWithoutFileName,true);

Discussion

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 specified in the TEMP environment variable.

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.

    [ Team LiB ] Previous Section Next Section