예제 #1
0
        // Normalizes path (can be longer than MAX_PATH) and adds \\?\ long path prefix
        internal static string NormalizeLongPath(string path, string parameterName)
        {
            if (path == null)
            {
                throw new ArgumentNullException(parameterName);
            }

            if (path.Length == 0)
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "'{0}' cannot be an empty string.", parameterName), parameterName);
            }

            StringBuilder buffer = new StringBuilder(path.Length + 1); // Add 1 for NULL
            uint          length = NativeMethods.GetFullPathName(path, (uint)buffer.Capacity, buffer, IntPtr.Zero);

            if (length > buffer.Capacity)
            {
                // Resulting path longer than our buffer, so increase it

                buffer.Capacity = (int)length;
                length          = NativeMethods.GetFullPathName(path, length, buffer, IntPtr.Zero);
            }

            if (length == 0)
            {
                throw LongPathCommon.GetExceptionFromLastWin32Error(parameterName);
            }

            if (length > NativeMethods.MAX_LONG_PATH)
            {
                throw LongPathCommon.GetExceptionFromWin32Error(NativeMethods.ERROR_FILENAME_EXCED_RANGE, parameterName);
            }

            return(AddLongPathPrefix(buffer.ToString()));
        }
예제 #2
0
        /// <summary>
        ///     Deletes the specified empty directory.
        /// </summary>
        /// <param name="path">
        ///      A <see cref="String"/> containing the path of the directory to delete.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="path"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="path"/> is an empty string (""), contains only white
        ///     space, or contains one or more invalid characters as defined in
        ///     <see cref="Path.GetInvalidPathChars()"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> contains one or more components that exceed
        ///     the drive-defined maximum length. For example, on Windows-based
        ///     platforms, components must not exceed 255 characters.
        /// </exception>
        /// <exception cref="PathTooLongException">
        ///     <paramref name="path"/> exceeds the system-defined maximum length.
        ///     For example, on Windows-based platforms, paths must not exceed
        ///     32,000 characters.
        /// </exception>
        /// <exception cref="DirectoryNotFoundException">
        ///     <paramref name="path"/> could not be found.
        /// </exception>
        /// <exception cref="UnauthorizedAccessException">
        ///     The caller does not have the required access permissions.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> refers to a directory that is read-only.
        /// </exception>
        /// <exception cref="IOException">
        ///     <paramref name="path"/> is a file.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> refers to a directory that is not empty.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> refers to a directory that is in use.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> specifies a device that is not ready.
        /// </exception>
        public static void Delete(string path)
        {
            string normalizedPath = LongPathCommon.NormalizeLongPath(path);

            if (!NativeMethods.RemoveDirectory(normalizedPath))
            {
                throw LongPathCommon.GetExceptionFromLastWin32Error();
            }
        }
예제 #3
0
        /// <summary>
        ///     Copies the specified file to a specified new file, indicating whether to overwrite an existing file.
        /// </summary>
        /// <param name="sourcePath">
        ///     A <see cref="String"/> containing the path of the file to copy.
        /// </param>
        /// <param name="destinationPath">
        ///     A <see cref="String"/> containing the new path of the file.
        /// </param>
        /// <param name="overwrite">
        ///     <see langword="true"/> if <paramref name="destinationPath"/> should be overwritten
        ///     if it refers to an existing file, otherwise, <see langword="false"/>.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is
        ///     <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is
        ///     an empty string (""), contains only white space, or contains one or more
        ///     invalid characters as defined in <see cref="Path.GetInvalidPathChars()"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/>
        ///     contains one or more components that exceed the drive-defined maximum length.
        ///     For example, on Windows-based platforms, components must not exceed 255 characters.
        /// </exception>
        /// <exception cref="PathTooLongException">
        ///     <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/>
        ///     exceeds the system-defined maximum length. For example, on Windows-based platforms,
        ///     paths must not exceed 32,000 characters.
        /// </exception>
        /// <exception cref="FileNotFoundException">
        ///     <paramref name="sourcePath"/> could not be found.
        /// </exception>
        /// <exception cref="DirectoryNotFoundException">
        ///     One or more directories in <paramref name="sourcePath"/> and/or
        ///     <paramref name="destinationPath"/> could not be found.
        /// </exception>
        /// <exception cref="UnauthorizedAccessException">
        ///     The caller does not have the required access permissions.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="overwrite"/> is true and <paramref name="destinationPath"/> refers to a
        ///     file that is read-only.
        /// </exception>
        /// <exception cref="IOException">
        ///     <paramref name="overwrite"/> is false and <paramref name="destinationPath"/> refers to
        ///     a file that already exists.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is a
        ///     directory.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="overwrite"/> is true and <paramref name="destinationPath"/> refers to
        ///     a file that already exists and is in use.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="sourcePath"/> refers to a file that is in use.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> specifies
        ///     a device that is not ready.
        /// </exception>
        public static void Copy(string sourcePath, string destinationPath, bool overwrite)
        {
            string normalizedSourcePath      = LongPathCommon.NormalizeLongPath(sourcePath, "sourcePath");
            string normalizedDestinationPath = LongPathCommon.NormalizeLongPath(destinationPath, "destinationPath");

            if (!NativeMethods.CopyFile(normalizedSourcePath, normalizedDestinationPath, !overwrite))
            {
                throw LongPathCommon.GetExceptionFromLastWin32Error();
            }
        }
예제 #4
0
        /// <summary>
        ///     Returns a value indicating whether the specified path refers to an existing directory.
        /// </summary>
        /// <param name="path">
        ///     A <see cref="String"/> containing the path to check.
        /// </param>
        /// <returns>
        ///     <see langword="true"/> if <paramref name="path"/> refers to an existing directory;
        ///     otherwise, <see langword="false"/>.
        /// </returns>
        /// <remarks>
        ///     Note that this method will return false if any error occurs while trying to determine
        ///     if the specified directory exists. This includes situations that would normally result in
        ///     thrown exceptions including (but not limited to); passing in a directory name with invalid
        ///     or too many characters, an I/O error such as a failing or missing disk, or if the caller
        ///     does not have Windows or Code Access Security (CAS) permissions to to read the directory.
        /// </remarks>
        public static bool Exists(string path)
        {
            bool isDirectory;

            if (LongPathCommon.Exists(path, out isDirectory))
            {
                return(isDirectory);
            }

            return(false);
        }
예제 #5
0
        private static SafeFileHandle GetFileHandle(string normalizedPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
        {
            NativeMethods.EFileAccess underlyingAccess = GetUnderlyingAccess(access);

            SafeFileHandle handle = NativeMethods.CreateFile(normalizedPath, underlyingAccess, (uint)share, IntPtr.Zero, (uint)mode, (uint)options, IntPtr.Zero);

            if (handle.IsInvalid)
            {
                throw LongPathCommon.GetExceptionFromLastWin32Error();
            }

            return(handle);
        }
예제 #6
0
        /// <summary>
        ///     Creates the specified directory.
        /// </summary>
        /// <param name="path">
        ///     A <see cref="String"/> containing the path of the directory to create.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="path"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="path"/> is an empty string (""), contains only white
        ///     space, or contains one or more invalid characters as defined in
        ///     <see cref="Path.GetInvalidPathChars()"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> contains one or more components that exceed
        ///     the drive-defined maximum length. For example, on Windows-based
        ///     platforms, components must not exceed 255 characters.
        /// </exception>
        /// <exception cref="PathTooLongException">
        ///     <paramref name="path"/> exceeds the system-defined maximum length.
        ///     For example, on Windows-based platforms, paths must not exceed
        ///     32,000 characters.
        /// </exception>
        /// <exception cref="DirectoryNotFoundException">
        ///     <paramref name="path"/> contains one or more directories that could not be
        ///     found.
        /// </exception>
        /// <exception cref="UnauthorizedAccessException">
        ///     The caller does not have the required access permissions.
        /// </exception>
        /// <exception cref="IOException">
        ///     <paramref name="path"/> is a file.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> specifies a device that is not ready.
        /// </exception>
        /// <remarks>
        ///     Note: Unlike <see cref="Directory.CreateDirectory(System.String)"/>, this method only creates
        ///     the last directory in <paramref name="path"/>.
        /// </remarks>
        public static void Create(string path)
        {
            string normalizedPath = LongPathCommon.NormalizeLongPath(path);

            if (!NativeMethods.CreateDirectory(normalizedPath, IntPtr.Zero))
            {
                // To mimic Directory.CreateDirectory, we don't throw if the directory (not a file) already exists
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != NativeMethods.ERROR_ALREADY_EXISTS || !LongPathDirectory.Exists(path))
                {
                    throw LongPathCommon.GetExceptionFromWin32Error(errorCode);
                }
            }
        }
예제 #7
0
        /// <summary>
        ///     Opens the specified file.
        /// </summary>
        /// <param name="path">
        ///     A <see cref="String"/> containing the path of the file to open.
        /// </param>
        /// <param name="access">
        ///     One of the <see cref="FileAccess"/> value that specifies the operations that can be
        ///     performed on the file.
        /// </param>
        /// <param name="mode">
        ///     One of the <see cref="FileMode"/> values that specifies whether a file is created
        ///     if one does not exist, and determines whether the contents of existing files are
        ///     retained or overwritten.
        /// </param>
        /// <param name="share">
        ///     One of the <see cref="FileShare"/> values specifying the type of access other threads
        ///     have to the file.
        /// </param>
        /// <param name="bufferSize">
        ///     An <see cref="Int32"/> containing the number of bytes to buffer for reads and writes
        ///     to the file, or 0 to specified the default buffer size, 1024.
        /// </param>
        /// <param name="options">
        ///     One or more of the <see cref="FileOptions"/> values that describes how to create or
        ///     overwrite the file.
        /// </param>
        /// <returns>
        ///     A <see cref="FileStream"/> that provides access to the file specified in
        ///     <paramref name="path"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="path"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="path"/> is an empty string (""), contains only white
        ///     space, or contains one or more invalid characters as defined in
        ///     <see cref="Path.GetInvalidPathChars()"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> contains one or more components that exceed
        ///     the drive-defined maximum length. For example, on Windows-based
        ///     platforms, components must not exceed 255 characters.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     <paramref name="bufferSize"/> is less than 0.
        /// </exception>
        /// <exception cref="PathTooLongException">
        ///     <paramref name="path"/> exceeds the system-defined maximum length.
        ///     For example, on Windows-based platforms, paths must not exceed
        ///     32,000 characters.
        /// </exception>
        /// <exception cref="DirectoryNotFoundException">
        ///     One or more directories in <paramref name="path"/> could not be found.
        /// </exception>
        /// <exception cref="UnauthorizedAccessException">
        ///     The caller does not have the required access permissions.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> refers to a file that is read-only and <paramref name="access"/>
        ///     is not <see cref="FileAccess.Read"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> is a directory.
        /// </exception>
        /// <exception cref="IOException">
        ///     <paramref name="path"/> refers to a file that is in use.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="path"/> specifies a device that is not ready.
        /// </exception>
        public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
        {
            const int DefaultBufferSize = 1024;

            if (bufferSize == 0)
            {
                bufferSize = DefaultBufferSize;
            }

            string normalizedPath = LongPathCommon.NormalizeLongPath(path);

            SafeFileHandle handle = GetFileHandle(normalizedPath, mode, access, share, options);

            return(new FileStream(handle, access, bufferSize, (options & FileOptions.Asynchronous) == FileOptions.Asynchronous));
        }
예제 #8
0
        private static IEnumerable <string> EnumerateFileSystemEntries(string path, string searchPattern, bool includeDirectories, bool includeFiles)
        {
            string normalizedSearchPattern = LongPathCommon.NormalizeSearchPattern(searchPattern);
            string normalizedPath          = LongPathCommon.NormalizeLongPath(path);

            // First check whether the specified path refers to a directory and exists
            FileAttributes attributes;
            int            errorCode = LongPathCommon.TryGetDirectoryAttributes(normalizedPath, out attributes);

            if (errorCode != 0)
            {
                throw LongPathCommon.GetExceptionFromWin32Error(errorCode);
            }

            return(EnumerateFileSystemIterator(normalizedPath, normalizedSearchPattern, includeDirectories, includeFiles));
        }
예제 #9
0
        private static SafeFindHandle BeginFind(string normalizedPathWithSearchPattern, out NativeMethods.WIN32_FIND_DATA findData)
        {
            SafeFindHandle handle = NativeMethods.FindFirstFile(normalizedPathWithSearchPattern, out findData);

            if (handle.IsInvalid)
            {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != NativeMethods.ERROR_FILE_NOT_FOUND)
                {
                    throw LongPathCommon.GetExceptionFromWin32Error(errorCode);
                }

                return(null);
            }

            return(handle);
        }
예제 #10
0
        private static IEnumerable <string> EnumerateFileSystemIterator(string normalizedPath, string normalizedSearchPattern, bool includeDirectories, bool includeFiles)
        {
            // NOTE: Any exceptions thrown from this method are thrown on a call to IEnumerator<string>.MoveNext()

            string path = LongPathCommon.RemoveLongPathPrefix(normalizedPath);

            NativeMethods.WIN32_FIND_DATA findData;
            using (SafeFindHandle handle = BeginFind(Path.Combine(normalizedPath, normalizedSearchPattern), out findData)) {
                if (handle == null)
                {
                    yield break;
                }

                do
                {
                    string currentFileName = findData.cFileName;

                    if (IsDirectory(findData.dwFileAttributes))
                    {
                        if (includeDirectories && !IsCurrentOrParentDirectory(currentFileName))
                        {
                            yield return(Path.Combine(path, currentFileName));
                        }
                    }
                    else
                    {
                        if (includeFiles)
                        {
                            yield return(Path.Combine(path, currentFileName));
                        }
                    }
                } while (NativeMethods.FindNextFile(handle, out findData));

                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != NativeMethods.ERROR_NO_MORE_FILES)
                {
                    throw LongPathCommon.GetExceptionFromWin32Error(errorCode);
                }
            }
        }