Use GetTempPath to locate appropriate storage for temporary files

Use GetTempPath to locate appropriate storage for temporary files

Benefits

Description

In the managed environment, it’s never been good practice to assume your application has sufficient privilege to read and write the local hard drive, or to assume that you know where the system administrator wants temporary storage placed. With the advent of Windows Terminals and thin clients, it’s not even safe to assume there is local storage!

To avoid issues like these it’s best to write all temporary files to the Windows temp folder. By default, the Windows temp folder exists and has read/write permission in all profiles. It is also the first place disk cleanup utilities look for leftover ~TMP files.

The path to the Windows temp folder is obtained by calling the Win32 API GetTempPath.

While it is possible to obtain the temp path by other means, note that an administrator can reconfigure the temp path at any time. This means that a call to GetTempPath each and every time is the only way to ensure you have a reliable path to which temporary files can be written.

When you are attempting to use an existing temp file it's a good idea to cache the last path returned before calling GetTempPath again to modify the file. If the two pathnames are different, copy the temp file to the newly returned location before performing the file modification.

Code Sample

We get the temp path, then append our filename to it. It’s important to remember the full path filename for the file since temp path can change while your program is running.

_TCHAR    tszBuf[MAX_PATH];

if (0 == GetTempPath(MAX_PATH, tszBuf))
{
    ASSERT(FALSE);
    // This shouldn't fail, but just in case it does...
    // Handle the error
}
if (!PathAppend(tszBuf, _T("~prg.tmp"))
{
	Assert(FALSE);
	// This shouldn't fail, but just in case it does...
	// Handle the error
}

// tszBuf now the full path and filename for the temp file.
// Remember it to access the file later.

Considerations

Don’t rely on disk utilities to clean up your temp files. Delete temporary files when you are finished with them, or upon application exit.

See Also

GetTempPath, PathAppend