Thursday, April 3, 2008

How to create unique temporary file name and folder.

        As we investigated, it is possible to get temporary Windows folder by method Path.GetTempPath and create temporary file by method Path.GetTempFileName().

Unfortunately, these methods cannot help us to create unique temporary folder or temporary file (method Path.GetTempFileName() can generate only 65 536 unique file names at the same time).

It is suggested to generate unique path and name to use a globally unique identifier (GUID) with help of method Guid.NewGuid(). "Such an identifier has a very low probability of being duplicated." by MSDN.

Method, which can generate unique temporary folder:

static string GetUniquePath()
{
string uniquePath;
do
{
Guid guid = Guid.NewGuid();
string uniqueSubFolderName = guid.ToString();
uniquePath = Path.GetTempPath() + uniqueSubFolderName;
} while (Directory.Exists(uniquePath));
Directory.CreateDirectory(uniquePath);
return uniquePath;
}


The method generated and created such paths:



C:\Documents and Settings\name-f\Local Settings\Temp\b0dc9b66-a32c-586c-815b-dfed844df58c



C:\Documents and Settings\name-f\Local Settings\Temp\18a09210-9107-4a19-ab11-a246c36fec54



By the same way, can be generated and created temporary file path.



Important notes:



1. Don't forget to delete created temporary folder and files after usage.



2. Published method GetUniquePath is not protected for multi-threaded usage.



Reference:



Guid Structure



Guid.NewGuid Method

No comments: