Create a directory, but don't fail if it already exists.

The standard .NET method Directory.CreateDirectory (string path) creates a directory (including parent directories, if needed) if it doesn't already exist, and returns a DirectoryInfo object for the created directory.

And if the directory already exists, it returns a DirectoryInfo object for the already existing directory.

I need a method that will create a directory if it doesn't already exist, but will fail - return an error or throw an exception - if the directory already exists.

And no, Directory.Exists (string) won't serve. I need something atomic. I interact with C ++ applications that were designed to have or not certain directories as locks, and using DirectoryExists () and then Directory.CreateDirectory () leaves a window to step on.

At the file system level, creating a directory is an atomic operation. If both processes try to do this, only one of them will be successful. And the API available for C ++ programs reflects this. The standard API in .NET hides this. Is there any lower level API that is not available?

+3


source to share


1 answer


Consider using native CreateDirectory via Interop :

internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool CreateDirectory(string lpPathName, IntPtr lpSecurityAttributes);
}

      



If it fails because the directory exists, the function returns false

and Marshal.GetLastWin32Error

should return ERROR_ALREADY_EXISTS

(decimal 183 or 0xB7) .

ERROR_ALREADY_EXISTS The specified directory already exists.

+6


source







All Articles