What's the best way to get a temp directory name in Windows? I see that I can use GetTempPath
and GetTempFileName
to create a temporary file, but is there any equivalent to the Linux / BSD mkdtemp
function for creating a temporary directory?
views:
1566answers:
4GetTempPath is the correct way of doing it; I'm not sure what your concern about this method is. You can then use CreateDirectory to make it.
No, there is no equivalent to mkdtemp. The best option is to use a combination of GetTempPath and GetRandomFileName.
You would need code similar to this:
public string GetTemporaryDirectory()
{
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);
return tempDirectory;
}
As mentioned above, Path.GetTempPath() is one way to do it. You could also call Environment.GetEnvironmentVariable("TEMP") if the user has a TEMP environment variable set up.
If you are planning on using the temp directory as a means of persisting data in the application, you probably should look at using IsolatedStorage as a repository for configuration/state/etc...
I like to use GetTempPath(), a GUID-creation function like CoCreateGuid(), and CreateDirectory().
A GUID is designed to have a high probability of uniqueness, and it's also highly improbable that someone would manually create a directory with the same form as a GUID (and if they do then CreateDirectory() will fail indicating its existence.)