Ejemplo n.º 1
0
        private SafeFindFileHandle FindFirstFile(string pathLp, out NativeMethods.WIN32_FIND_DATA win32FindData)
        {
            var searchOption = null != FileSystemObjectType && (bool)FileSystemObjectType
            ? NativeMethods.FINDEX_SEARCH_OPS.SearchLimitToDirectories
            : NativeMethods.FINDEX_SEARCH_OPS.SearchNameMatch;


            var handle = Transaction == null || !NativeMethods.IsAtLeastWindowsVista

                         // FindFirstFileEx() / FindFirstFileTransacted()
                         // In the ANSI version of this function, the name is limited to MAX_PATH characters.
                         // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
                         // 2013-01-13: MSDN confirms LongPath usage.

                         // A trailing backslash is not allowed.
            ? NativeMethods.FindFirstFileEx(Path.RemoveTrailingDirectorySeparator(pathLp, false), FindExInfoLevel, out win32FindData, searchOption, IntPtr.Zero, LargeCache)
            : NativeMethods.FindFirstFileTransacted(Path.RemoveTrailingDirectorySeparator(pathLp, false), FindExInfoLevel, out win32FindData, searchOption, IntPtr.Zero, LargeCache, Transaction.SafeHandle);

            var lastError = Marshal.GetLastWin32Error();

            if (handle.IsInvalid)
            {
                handle.Close();
                handle = null;

                if (!ContinueOnException)
                {
                    ThrowPossibleException((uint)lastError, pathLp);
                }
            }

            return(handle);
        }
Ejemplo n.º 2
0
        private SafeFindFileHandle FindFirstFile(string pathLp, out NativeMethods.WIN32_FIND_DATA win32FindData, bool suppressException = false)
        {
            int lastError;
            var searchOption = null != FileSystemObjectType && (bool)FileSystemObjectType ? NativeMethods.FINDEX_SEARCH_OPS.SearchLimitToDirectories : NativeMethods.FINDEX_SEARCH_OPS.SearchNameMatch;

            var handle = FileSystemInfo.FindFirstFileNative(Transaction, pathLp, FindExInfoLevel, searchOption, LargeCache, out lastError, out win32FindData);


            if (!suppressException && !ContinueOnException)
            {
                if (null == handle)
                {
                    switch ((uint)lastError)
                    {
                    case Win32Errors.ERROR_FILE_NOT_FOUND: // FileNotFoundException.
                    case Win32Errors.ERROR_PATH_NOT_FOUND: // DirectoryNotFoundException.
                    case Win32Errors.ERROR_NOT_READY:      // DeviceNotReadyException: Floppy device or network drive not ready.

                        Directory.ExistsDriveOrFolderOrFile(Transaction, pathLp, IsDirectory, lastError, true, true);
                        break;
                    }


                    ThrowPossibleException((uint)lastError, pathLp);
                }

                //// When the handle is null and we are still here, it means the ErrorHandler is active, preventing the Exception from being thrown.

                //if (null != handle)
                //   VerifyInstanceType(win32FindData);
            }


            return(handle);
        }
Ejemplo n.º 3
0
        private SafeFindFileHandle FindFirstFile(string pathLp, out NativeMethods.WIN32_FIND_DATA win32FindData)
        {
            var handle = Transaction == null || !NativeMethods.IsAtLeastWindowsVista

                         // FindFirstFileEx() / FindFirstFileTransacted()
                         // In the ANSI version of this function, the name is limited to MAX_PATH characters.
                         // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
                         // 2013-01-13: MSDN confirms LongPath usage.

                         // A trailing backslash is not allowed.
            ? NativeMethods.FindFirstFileEx(Path.RemoveTrailingDirectorySeparator(pathLp, false), FindExInfoLevel, out win32FindData, _limitSearchToDirs, IntPtr.Zero, LargeCache)
            : NativeMethods.FindFirstFileTransacted(Path.RemoveTrailingDirectorySeparator(pathLp, false), FindExInfoLevel, out win32FindData, _limitSearchToDirs, IntPtr.Zero, LargeCache, Transaction.SafeHandle);

            var lastError = Marshal.GetLastWin32Error();

            if (handle.IsInvalid)
            {
                handle.Close();
                handle = null;

                if (!ContinueOnException)
                {
                    switch ((uint)lastError)
                    {
                    case Win32Errors.ERROR_FILE_NOT_FOUND:
                    case Win32Errors.ERROR_PATH_NOT_FOUND:
                        // MSDN: .NET 3.5+: DirectoryNotFoundException: Path is invalid, such as referring to an unmapped drive.
                        // Directory.Delete()

                        NativeError.ThrowException(IsDirectory ? (int)Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND, pathLp);
                        break;

                    case Win32Errors.ERROR_DIRECTORY:
                        // MSDN: .NET 3.5+: IOException: path is a file name.
                        // Directory.EnumerateDirectories()
                        // Directory.EnumerateFiles()
                        // Directory.EnumerateFileSystemEntries()
                        // Directory.GetDirectories()
                        // Directory.GetFiles()
                        // Directory.GetFileSystemEntries()

                        NativeError.ThrowException(lastError, pathLp);
                        break;

                    case Win32Errors.ERROR_ACCESS_DENIED:
                        // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission.
                        NativeError.ThrowException(lastError, pathLp);
                        break;
                    }

                    // MSDN: .NET 3.5+: IOException
                    NativeError.ThrowException(lastError, pathLp);
                }
            }

            return(handle);
        }
Ejemplo n.º 4
0
        private T NewFileSystemEntryType <T>(bool isFolder, NativeMethods.WIN32_FIND_DATA win32FindData, string fileName, string pathLp)
        {
            // Determine yield, e.g. don't return files when only folders are requested and vice versa.
            if (null != FileSystemObjectType && (!(bool)FileSystemObjectType || !isFolder) && (!(bool)!FileSystemObjectType || isFolder))
            {
                return((T)(object)null);
            }

            // Determine yield.
            if (null != fileName && !(_nameFilter == null || (_nameFilter != null && _nameFilter.IsMatch(fileName))))
            {
                return((T)(object)null);
            }


            var fullPathLp = (IsRelativePath ? OriginalInputPath + Path.DirectorySeparator : pathLp) + (!Utils.IsNullOrWhiteSpace(fileName) ? fileName : string.Empty);


            // Return object instance FullPath property as string, optionally in long path format.
            if (AsString)
            {
                return((T)(object)(AsLongPath ? fullPathLp : Path.GetRegularPathCore(fullPathLp, GetFullPathOptions.None, false)));
            }


            // Make sure the requested file system object type is returned.
            // null = Return files and directories.
            // true = Return only directories.
            // false = Return only files.

            var fsei = new FileSystemEntryInfo(win32FindData)
            {
                FullPath = fullPathLp
            };

            return(AsFileSystemInfo
                   // Return object instance of type FileSystemInfo.
            ? (T)(object)(fsei.IsDirectory
               ? (FileSystemInfo)
                          new DirectoryInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            }
               : new FileInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            })

                   // Return object instance of type FileSystemEntryInfo.
            : (T)(object)fsei);
        }
Ejemplo n.º 5
0
        private T NewFileSystemEntryType <T>(NativeMethods.WIN32_FIND_DATA win32FindData, string fileName, string pathLp, bool isFolder)
        {
            // Determine yield.
            if (FileSystemObjectType != null && (!(bool)FileSystemObjectType || !isFolder) && (!(bool)!FileSystemObjectType || isFolder))
            {
                return((T)(object)null);
            }


            var fullPathLp = string.Format(CultureInfo.InvariantCulture, "{0}{1}", pathLp, fileName ?? string.Empty);


            // Return object instance FullPath property as string, optionally in long path format.
            if (AsString)
            {
                return((T)(object)(IsRelativePath
               ? fullPathLp
               : (AsLongPath ? fullPathLp : Path.GetRegularPathCore(fullPathLp, GetFullPathOptions.None, false))));
            }


            // Make sure the requested file system object type is returned.
            // null = Return files and directories.
            // true = Return only directories.
            // false = Return only files.

            var fsei = new FileSystemEntryInfo(win32FindData)
            {
                FullPath = !fullPathLp.StartsWith(Path.CurrentDirectoryPrefix, StringComparison.OrdinalIgnoreCase)
               ? fullPathLp
               : Path.CombineCore(false, InputPath, fileName)
            };


            return(AsFileSystemInfo
                   // Return object instance of type FileSystemInfo.
            ? (T)(object)(fsei.IsDirectory
               ? (FileSystemInfo)
                          new DirectoryInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            }
               : new FileInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            })

                   // Return object instance of type FileSystemEntryInfo.
            : (T)(object)fsei);
        }
Ejemplo n.º 6
0
        private void VerifyInstanceType(NativeMethods.WIN32_FIND_DATA win32FindData)
        {
            var regularPath = Path.GetCleanExceptionPath(InputPath);

             var isFolder = (win32FindData.dwFileAttributes & FileAttributes.Directory) != 0;

             if (IsDirectory)
             {
            if (!isFolder)
               throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_PATH_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_Directory_Is_A_File, regularPath)));
             }

             else if (isFolder)
            throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "({0}) {1}", Win32Errors.ERROR_FILE_NOT_FOUND, string.Format(CultureInfo.InvariantCulture, Resources.Target_File_Is_A_Directory, regularPath)));
        }
        private T NewFileSystemEntryType <T>(NativeMethods.WIN32_FIND_DATA win32FindData, string fullPathLp, bool isFolder)
        {
            // Determine yield.
            if (FileSystemObjectType != null && ((!(bool)FileSystemObjectType || !isFolder) && (!(bool)!FileSystemObjectType || isFolder)))
            {
                return((T)(object)null);
            }

            if (AsString)
            {
                // Return object instance FullPath property as string, optionally in long path format.
                return((T)(object)(AsLongPath ? fullPathLp : Path.GetRegularPathCore(fullPathLp, GetFullPathOptions.None)));
            }


            // Make sure the requested file system object type is returned.
            // null = Return files and directories.
            // true = Return only directories.
            // false = Return only files.

            var fsei = new FileSystemEntryInfo(win32FindData)
            {
                FullPath = fullPathLp
            };

            return(AsFileSystemInfo
                   // Return object instance of type FileSystemInfo.
            ? (T)(object)(fsei.IsDirectory
               ? (FileSystemInfo)
                          new DirectoryInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            }
               : new FileInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            })

                   // Return object instance of type FileSystemEntryInfo.
            : (T)(object)fsei);
        }
Ejemplo n.º 8
0
        internal static SafeFindFileHandle FindFirstFileNative(KernelTransaction transaction, string pathLp, NativeMethods.FINDEX_INFO_LEVELS infoLevel, NativeMethods.FINDEX_SEARCH_OPS searchOption, NativeMethods.FIND_FIRST_EX_FLAGS additionalFlags, out int lastError, out NativeMethods.WIN32_FIND_DATA win32FindData)
        {
            var safeHandle = transaction == null || !NativeMethods.IsAtLeastWindowsVista

                             // FindFirstFileEx() / FindFirstFileTransacted()
                             // 2013-01-13: MSDN confirms LongPath usage.

                             // A trailing backslash is not allowed.
            ? NativeMethods.FindFirstFileEx(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags)
            : NativeMethods.FindFirstFileTransacted(Path.RemoveTrailingDirectorySeparator(pathLp), infoLevel, out win32FindData, searchOption, IntPtr.Zero, additionalFlags, transaction.SafeHandle);

            lastError = Marshal.GetLastWin32Error();

            if (!NativeMethods.IsValidHandle(safeHandle, false))
            {
                safeHandle = null;
            }


            return(safeHandle);
        }
 /// <summary>Initializes a new instance of the <see cref="FileSystemEntryInfo"/> class.</summary>
 /// <param name="findData">The NativeMethods.WIN32_FIND_DATA structure.</param>
 internal FileSystemEntryInfo(NativeMethods.WIN32_FIND_DATA findData)
 {
     Win32FindData = findData;
 }
        public T Get <T>()
        {
            using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
            {
                NativeMethods.WIN32_FIND_DATA win32FindData;


                // Not explicitly set to be a folder.

                if (!IsDirectory)
                {
                    using (var handle = FindFirstFile(InputPath, out win32FindData))

                        return(null == handle

                     ? (T)(object)null

                     : NewFileSystemEntryType <T>((win32FindData.dwFileAttributes & FileAttributes.Directory) != 0, null, null, InputPath, win32FindData));
                }


                using (var handle = FindFirstFile(InputPath, out win32FindData, true))
                {
                    if (null == handle)
                    {
                        // InputPath might be a logical drive such as: "C:\", "D:\".

                        var attrs = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();

                        var lastError = File.FillAttributeInfoCore(Transaction, Path.GetRegularPathCore(InputPath, GetFullPathOptions.None, false), ref attrs, false, true);
                        if (lastError != Win32Errors.NO_ERROR)
                        {
                            if (!ContinueOnException)
                            {
                                switch ((uint)lastError)
                                {
                                case Win32Errors.ERROR_FILE_NOT_FOUND: // FileNotFoundException.
                                case Win32Errors.ERROR_PATH_NOT_FOUND: // DirectoryNotFoundException.
                                case Win32Errors.ERROR_NOT_READY:      // DeviceNotReadyException: Floppy device or network drive not ready.
                                case Win32Errors.ERROR_BAD_NET_NAME:

                                    Directory.ExistsDriveOrFolderOrFile(Transaction, InputPath, IsDirectory, lastError, true, true);
                                    break;
                                }

                                ThrowPossibleException((uint)lastError, InputPath);
                            }

                            return((T)(object)null);
                        }


                        win32FindData = new NativeMethods.WIN32_FIND_DATA
                        {
                            cFileName        = Path.CurrentDirectoryPrefix,
                            dwFileAttributes = attrs.dwFileAttributes,
                            ftCreationTime   = attrs.ftCreationTime,
                            ftLastAccessTime = attrs.ftLastAccessTime,
                            ftLastWriteTime  = attrs.ftLastWriteTime,
                            nFileSizeHigh    = attrs.nFileSizeHigh,
                            nFileSizeLow     = attrs.nFileSizeLow
                        };
                    }


                    VerifyInstanceType(win32FindData);
                }


                return(NewFileSystemEntryType <T>((win32FindData.dwFileAttributes & FileAttributes.Directory) != 0, null, null, InputPath, win32FindData));
            }
        }
        private T NewFileSystemEntryType <T>(bool isFolder, FileSystemEntryInfo fsei, string fileName, string pathLp, NativeMethods.WIN32_FIND_DATA win32FindData)
        {
            // Determine yield, e.g. don't return files when only folders are requested and vice versa.
            if (null != FileSystemObjectType && (!(bool)FileSystemObjectType || !isFolder) && (!(bool)!FileSystemObjectType || isFolder))
            {
                return((T)(object)null);
            }


            // Determine yield.
            if (null != fileName && !(_nameFilter == null || _nameFilter != null && _nameFilter.IsMatch(fileName)))
            {
                return((T)(object)null);
            }


            if (null == fsei)
            {
                fsei = NewFilesystemEntry(pathLp, fileName, win32FindData);
            }


            // Return object instance FullPath property as string, optionally in long path format.

            return(AsString
            ? null == InclusionFilter || InclusionFilter(fsei)
               ? (T)(object)(AsLongPath ? fsei.LongFullPath : fsei.FullPath)
               : (T)(object)null


                   // Make sure the requested file system object type is returned.
                   // null = Return files and directories.
                   // true = Return only directories.
                   // false = Return only files.

            : null != InclusionFilter && !InclusionFilter(fsei)
               ? (T)(object)null

                   // Return object instance of type FileSystemInfo.

               : AsFileSystemInfo
                  ? (T)(object)(fsei.IsDirectory

                     ? (FileSystemInfo) new DirectoryInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            }

                     : new FileInfo(Transaction, fsei.LongFullPath, PathFormat.LongFullPath)
            {
                EntryInfo = fsei
            })

                   // Return object instance of type FileSystemEntryInfo.

                  : (T)(object)fsei);
        }
 private FileSystemEntryInfo NewFilesystemEntry(string pathLp, string fileName, NativeMethods.WIN32_FIND_DATA win32FindData)
 {
     return(new FileSystemEntryInfo(win32FindData)
     {
         FullPath = (IsRelativePath ? OriginalInputPath + Path.DirectorySeparator : pathLp) + fileName
     });
 }
Ejemplo n.º 13
0
        private FileSystemEntryInfo NewFilesystemEntry(string pathLp, string fileName, NativeMethods.WIN32_FIND_DATA win32FindData)
        {
            var fullPath = (IsRelativePath ? pathLp.Replace(RelativeAbsolutePrefix, string.Empty) : pathLp) + fileName;

            return(new FileSystemEntryInfo(win32FindData)
            {
                FullPath = fullPath
            });
        }
Ejemplo n.º 14
0
        public bool MoveNext()
        {
            NativeMethods.WIN32_FIND_DATA findData = new NativeMethods.WIN32_FIND_DATA();

            if (mHandle == null)
            {
                if (mTransaction == null)
                {
                    mHandle = NativeMethods.FindFirstFileExW(mSearchString,
                                                             NativeMethods.FINDEX_INFO_LEVELS.FindExInfoStandard,
                                                             findData, mFindexSearchOptions,
                                                             IntPtr.Zero, NativeMethods.FINDEX_FLAGS.FIND_FIRST_EX_NONE);
                }
                else
                {
                    mHandle = NativeMethods.FindFirstFileTransactedW(mSearchString,
                                                                     NativeMethods.FINDEX_INFO_LEVELS.FindExInfoStandard,
                                                                     findData, mFindexSearchOptions, IntPtr.Zero,
                                                                     NativeMethods.FINDEX_FLAGS.FIND_FIRST_EX_NONE, mTransaction.SafeHandle);
                }

                if (mHandle.IsInvalid)
                {
                    uint error = (uint)Marshal.GetLastWin32Error();
                    if (error == Win32Errors.ERROR_FILE_NOT_FOUND)
                    {
                        return(false);
                    }
                    else
                    {
                        NativeError.ThrowException(error, mSearchString, mSearchString);
                    }
                }
                mSysEntryInfo = new FileSystemEntryInfo(findData);
                return(Filter());
            }
            else if (mHandle.IsInvalid)
            {
                return(false);
            }
            else
            {
                if (!NativeMethods.FindNextFileW(mHandle, findData))
                {
                    uint error = (uint)Marshal.GetLastWin32Error();
                    if (error == Win32Errors.ERROR_NO_MORE_FILES)
                    {
                        mHandle.Close();
                        return(false);
                    }
                    else
                    {
                        NativeError.ThrowException(error);
                    }
                }
                else
                {
                    mSysEntryInfo = new FileSystemEntryInfo(findData);
                    return(Filter());
                }
            }
            // Actually unreachable code, but seems to be neccessary.
            return(false);
        }
Ejemplo n.º 15
0
        private FileSystemEntryInfo NewFilesystemEntry(string pathLp, string fileName, NativeMethods.WIN32_FIND_DATA win32FindData)
        {
            var fullPath = (IsRelativePath ? pathLp.Replace(RelativeAbsolutePrefix, string.Empty) : pathLp) + fileName;

             return new FileSystemEntryInfo(win32FindData) {FullPath = fullPath};

             //return new FileSystemEntryInfo(win32FindData) {FullPath = (IsRelativePath ? OriginalInputPath + Path.DirectorySeparator : pathLp) + fileName};
        }