Question

What's the best way to get a string containing a folder name that I can be certain does not exist? That is, if I call DirectoryInfo.Exists for the given path, it should return false.

EDIT: The reason behind it is I am writing a test for an error checker, the error checker tests whether the path exists, so I wondered aloud on the best way to get a path that doesn't exist.

Was it helpful?

Solution

Name it after a GUID - just take out the illegal characters.

OTHER TIPS

There isn't really any way to do precisely what you way you want to do. If you think about it, you see that even after the call to DirectoryInfo.Exists has returned false, some other program could have gone ahead and created the directory - this is a race condition.

The normal method to handle this is to create a new temporary directory - if the creation succeeds, then you know it hadn't existed before you created it.

Well, without creating the directory, all you can be sure of is that it didn't exist a few microseconds ago. Here's one approach that might be close enough:

        string path = Path.GetTempFileName();
        File.Delete(path);
        Directory.CreateDirectory(path);

Note that this creates the directory to block against thread races (i.e. another process/thread stealing the directory from under you).

What I ended up using:

using System.IO;

string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

(Also, it doesn't seem like you need to strip out chars from a guid - they generate legal filenames)

Well, one good bet will be to concatenate strings like the user name, today's date, and time down to the millisecond.

I'm curious though: Why would you want to do this? What should it be for?

Is this to create a temporary folder or something? I often use Guid.NewGuid to get a string to use for the folder name that you want to be sure does not already exist.

I think you can be close enough:

string directoryName = Guid.NewGuid.ToSrtring();

Since Guid's are fairly random you should not get 2 dirs the same.

Using a freshly generated GUID within a namespace that is also somewhat unique (for example, the name of your application/product) should get you what you want. For example, the following code is extremely unlikely to fail:

string ParentPath = System.IO.Path.Combine(Environment.GetEnvironmentVariable("TEMP"), "MyAppName");
string UniquePath = System.IO.Path.Combine(ParentPath, Guid.NewGuid().ToString());
System.IO.Directory.CreateDirectory(UniquePath);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top