
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Opening a File Stream with Just a File Handle
|
723
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 follow-
ing line of code deletes this file:
File.Delete(tempFilePathWithFileName);
The GetTempFileName method creates the temporary file and returns the path, includ-
ing 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( );
Discussion
You should use a temporary file whenever you need to store information tempo-
rarily for later retrieval. The one thing you must remember is to delete this tempo-
rary 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