Exemplo n.º 1
0
        /// <summary>
        /// Creates a new directory. If <paramref name="recursive"/> is false, the parent directory must exists.
        /// </summary>
        /// <param name="uncDirectoryPath">Directory path</param>
        /// <param name="recursive">If <paramref name="recursive"/> is false, the parent directory must exist.</param>
        /// <exception cref="PathAlreadyExistsException">The specified path already exists.</exception>
        /// <exception cref="PathNotFoundException">This error is fired if the specified path or a part of them does not exist.</exception>
        public static void CreateDirectory(string uncDirectoryPath, bool recursive = false)
        {
            Contract.Requires(!String.IsNullOrEmpty(uncDirectoryPath));

            // cancel if path exists
            if (Exists(uncDirectoryPath))
            {
                return;
            }

            // cancel if requested path is root
            if (QuickIOPath.IsRoot(uncDirectoryPath))
            {
                throw new InvalidOperationException("A root directory cannot be created.");
            }

            // create parent directory if accepted
            if (recursive)
            {
                string parent = QuickIOPath.GetDirectoryName(uncDirectoryPath);
                if (parent == null)
                {
                    throw new InvalidOperationException("Parent directory does not exists and cannot be created.");
                }

                Stack <string> stack = new Stack <string>();
                stack.Push(parent);

                while (stack.Count > 0)
                {
                    string currentDirectory = stack.Pop();

                    if (QuickIOPath.IsRoot(currentDirectory))
                    {
                        if (!QuickIOPath.Exists(currentDirectory))
                        {
                            throw new InvalidOperationException("A root directory cannot be created.");
                        }
                    }
                    else
                    {
                        // no root path here
                        if (!Win32SafeNativeMethods.CreateDirectory(currentDirectory, IntPtr.Zero))
                        {
                            Win32ErrorCodes.NativeExceptionMapping(currentDirectory, Marshal.GetLastWin32Error());
                        }
                    }
                }
            }
        }