Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create unique directory

Status
Not open for further replies.

newDBA

MIS
Nov 8, 2001
21
FR
I need to create a unique directory name but I see a problem using the following approach.

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.
 
You can use Path.GetTempPath to find out the user's temporary directory.

If you needed an unique directory beneath that, all your own, you could get the value of Path.GetTempFileName and use that to create your own directory.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Unless the OS supports a function that creates a directory only if it doesn't exist, I don't see any way to be 100% sure that no other process created it before you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top