Cry about...
Delphi Programming


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):

  1. By reading the value of the TEMP environment variable
  2. GetTempPath API function

TEMP environment variable

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

Note:

  • You will need to include SysUtils to use the GetEnvironmentVariable function. The version in SysUtils places a wrapper around the API version of the function defined in the unit Windows (which takes different parameters).

GetTempPath API function

The Windows API function GetTempPath returns the path to the Windows temporary file folder. The GetTempPath function 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;

Note:

  • GetTempPath and MAX_PATH are defined in the unit Windows.
  • StrPas is defined in the unit SysUtils.

These notes are believed to be correct for Delphi 6 and Delphi 7 and may apply to other versions as well.



About the author: 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.