Correct location to save a temporary file in Windows?

I have a file I need to write to a temp location, what is the best place in Windows? This file needs to not move as I need to read it a couple of times and dispose it when I close the program.


Solution 1:

use

Path.GetTempPath();

or

Path.GetTempFileName();

As commentator pointed out, GetTempFileName() is not threadsafe - but you can construct unique file names based on GUIDs.

Solution 2:

The others beat me to it regarding

System.IO.Path.GetTempPath()

But you can also look into application data folder. That will allow you more control over your file, like the ability have 1 shared for all users or 1 per user.

Application.CommonAppDataPath
Application.UserAppDataPath

Solution 3:

Use the Windows API function GetTempPath() from System.IO.Path (see MSDN)

using System.IO

...

myTempPath = Path.GetTempPath();

You should be aware that the filesystem might well change during your program's execution. Either the Temp path may change (unlikely, granted), or your temporary file might have been moved or deleted by the user.

Be prepared to check for its existence each time you access it and handle the case when it's not found gracefully.