Is there a way to be sure that I am the one that created a directory in C#? By default, Directory.CreateDirectory
is essentially an UPSERT operation: If the directory doesn’t exist, it is created, but if it does already exist, well that’s just fine. As long as it exists on return, everybody is happy. But, I intend to delete the subtree when I’m done with it, and I don’t want to do that if I didn’t create it in the first place. As far as I can tell, the only way to achieve this will be P/Invoke because with the managed API, I must test for existence separately and there’ll always be a race condition between Directory.Exists
and Directory.CreateDirectory
. In the underlying platform API, though, the call to create a directory will return an error if it already exists (ERROR_ALREADY_EXISTS
from CreateDirectoryW
on Windows, EEXIST
from mkdir
on POSIX systems). Is there a managed way to create a directory but only if it doesn’t exist in .NET?