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开发者_如何学C 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)?
You could use Guid.NewGuid().ToString()
for that task.
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;
}
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!
}
You can create unique name with Guid.
精彩评论