Jez
Jez

Reputation: 30073

GetTempFileName function for a directory?

The .NET Framework defines a System.IO.Path.GetTempFileName method, which guarantees that the temporary filename it generates will be unique. As far as I can tell though, although extremely unlikely, this filename could be identical to the name of a directory at the same path, meaning that I can't assume that by taking the name of that file, deleting it, and creating a directory of the same name, I'll have a directory with a unique name to any other directory. Whatsmore, I can't specify the path under which GetTempFileName should create its temp file. There doesn't seem to be an equivalent function to GetTempFileName for directories.

Is there a GetTempFileName equivalent for creating a unique directory? If not, what's the best way to create a unique directory at a specified location (ie. I specify the path under which to create the unique directory)?

Upvotes: 18

Views: 11085

Answers (4)

EM0
EM0

Reputation: 6337

Guid works, but if you want a shorter directory name (8.3 format) you can use GetRandomFileName():

    public static string GetRandomTempPath()
    {
        var tempDir = System.IO.Path.GetTempPath();

        string fullPath;
        do
        {
            var randomName = System.IO.Path.GetRandomFileName();
            fullPath = System.IO.Path.Combine(tempDir, randomName);
        }
        while (Directory.Exists(fullPath));

        return fullPath;
    }

Upvotes: 11

DanielB
DanielB

Reputation: 20230

You could use Guid.NewGuid().ToString() for that task.

Upvotes: 24

LukeH
LukeH

Reputation: 269528

string basePath = @"c:\test\";    // or use Path.GetTempPath

string tempPath;
do
{
    tempPath = Path.Combine(basePath, Guid.NewGuid().ToString("N"));
} while (Directory.Exists(tempPath));

try
{
    Directory.CreateDirectory(tempPath);
}
catch
{
    // something went wrong!
}

Upvotes: 7

Kieran Dang
Kieran Dang

Reputation: 447

You can create unique name with Guid.

Upvotes: 1

Related Questions