Getting a safe temp catalog to use in your program

How to create a temp catalog in a good way where user access permissions are concerned.

Update note: I was focusing on Environment variables when I wrote this post and forgot about the other way to skin a cat (and I’m sure there are even more than two ways): using the static method on the System.IO.Path class. So now there is more than one way to do it below.

Ever tried to create a temp catalog from your program like so:

string temporaryDirectoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Guid.NewGuid().ToString("N"));

Well… or something similar. Get the current dir that you are executing in and create a subfolder.

Guess what: This is dangerous! If you want to be a nice little UAC aware coder this might be a problem. What if your code runs in a dir where you don’t have write permissions?

Here’s the solution: Extract method and try to get the Environment variable “TEMP” which is a temp directory in your current user directory which will look something like

C:\Users\<current user name>\AppData\Local\Temp

This code works:

string temporaryDirectoryPath = GetTempDirPath();

private static string GetTempDirPath()
{
    string temporaryDirectoryPath = Environment.GetEnvironmentVariable("TEMP");
    if (string.IsNullOrEmpty(temporaryDirectoryPath))
        temporaryDirectoryPath = AppDomain.CurrentDomain.BaseDirectory;

    return Path.Combine(temporaryDirectoryPath, Guid.NewGuid().ToString("N"));
}

As you can see I even included a fallback to the original solution if the environment variable does not exist.

This little code snippet should solve any write permission issues when you want a temp catalog in your program.

And then there’s the other way that does not require you to know the name of a particular Environment variable and you don’t even have to rely upon it.

All you need to do is call System.IO.Path.GetTempPath(); and this will give you exactly the same temp path as the code above. In fact if you inspect the implementations of both versions by looking into mscorlib using for instance Reflector you’ll see that you both methods make calls out to som Win32Native code. Exactly what happens out there I will leave as an exercise to the reader! (Another cool method is the Path.GetTempFileName() method that will create an empty file in a temp directory and give you a path to it’s name – and also there is Path.GetRandomFileName().)

Cheers,

M.

Technorati Tags:
Digg This

posted @ Thursday, November 27, 2008 7:19 PM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 5 and 4 and type the answer here:
 

Live Comment Preview: