How to get the Windows temporary directory
There are at least two ways to get the Windows temporary directory folder (i.e. that folder in which by convention applications may freely create temporary files):
The TEMP environment variable dates back to the pre-windows days of DOS, but is still used and available in windows applications. By convention both the variables TMP and TEMP indicate the temporary directory. The values of these variables can be easily read using the GetEnvironmentVariable function, i.e.:
t := GetEnvironmentVariable('TEMP');
- You will need to include
SysUtilsto use the
GetEnvironmentVariablefunction. The version in
SysUtilsplaces a wrapper around the API version of the function defined in the unit Windows (which takes different parameters).
The Windows API function
GetTempPath returns the path to
the Windows temporary file folder. The
is defined in the Windows unit and its definition looks like:
function GetTempPath(nBufferLength: Cardinal; lpBuffer: PChar): Cardinal;
This takes a buffer and the size of the buffer and writes the temporary folder into the buffer, returning the number of characters written to the buffer.
Personally I don't find this useful, because I prefer to be able to assign the value to a variable directly. For this reason I use a wrapper function:
function GetTempDirectory: String; var tempFolder: array[0..MAX_PATH] of Char; begin GetTempPath(MAX_PATH, @tempFolder); result := StrPas(tempFolder); end;
This lets you do more intuitive assignments such as
t := GetTempDirectory;
MAX_PATHare defined in the unit Windows.
StrPasis defined in the unit
These notes are believed to be correct for Delphi 6 and Delphi 7 and may apply to other versions as well.
About the author: Brian Cryer is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.