I need to create a unique directory name but I see a problem using the following approach.
The problem is that another process could create the directory after the Exists method is called.
Is there a way to only create a directory is it doesn't already exist in one step? Or, is there a way to get a return value that will tell me whether is was created or not? Calling Directory.CreateDirectory(path) will return a DirectoryInfo object regardless of whether a new dir was created or whether it already existed.
(I guess if all else fails I lock on some variable to synchronize access to the code that creates the directory...but I'd like to find a better approach)
Thanks.
Code:
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
The problem is that another process could create the directory after the Exists method is called.
Code:
if (!Directory.Exists(path))
{
==> another process/thread now creates the same directory <==
Directory.CreateDirectory(path);
}
Is there a way to only create a directory is it doesn't already exist in one step? Or, is there a way to get a return value that will tell me whether is was created or not? Calling Directory.CreateDirectory(path) will return a DirectoryInfo object regardless of whether a new dir was created or whether it already existed.
(I guess if all else fails I lock on some variable to synchronize access to the code that creates the directory...but I'd like to find a better approach)
Thanks.