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.