@Chris. I, too, was obsessed with the remote risk that a temporary directory might already exist. Discussions about random and cryptographically strong do not completely satisfy me.
My approach is based on the fundamental fact that O / S does not allow two calls to create a file for both. It's a little surprising that the .NET developers decided to hide the functionality of the Win32 API for directories, which makes it much easier since it returns an error when trying to create a directory for the second time. Here is what I use:
[DllImport(@"kernel32.dll", EntryPoint = "CreateDirectory", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CreateDirectoryApi ([MarshalAs(UnmanagedType.LPTStr)] string lpPathName, IntPtr lpSecurityAttributes); /// <summary> /// Creates the directory if it does not exist. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <returns>Returns false if directory already exists. Exceptions for any other errors</returns> /// <exception cref="System.ComponentModel.Win32Exception"></exception> internal static bool CreateDirectoryIfItDoesNotExist([NotNull] string directoryPath) { if (directoryPath == null) throw new ArgumentNullException("directoryPath"); // First ensure parent exists, since the WIN Api does not CreateParentFolder(directoryPath); if (!CreateDirectoryApi(directoryPath, lpSecurityAttributes: IntPtr.Zero)) { Win32Exception lastException = new Win32Exception(); const int ERROR_ALREADY_EXISTS = 183; if (lastException.NativeErrorCode == ERROR_ALREADY_EXISTS) return false; throw new System.IO.IOException( "An exception occurred while creating directory'" + directoryPath + "'".NewLine() + lastException); } return true; }
You can decide if the "cost / risk" of the unmanaged p / invoke code is worth it. Most would say that this is not so, but at least you now have a choice.
CreateParentFolder () remains as an exercise for the student. I am using Directory.CreateDirectory (). Be careful when getting the parent directory as it is null when it is in the root.
Andrew Dennison Jan 10 '16 at 10:42 on 2016-01-10 22:42
source share