private void Init() { WIN32_FIND_DATAW findData = new WIN32_FIND_DATAW(); string searchPath = Path.Combine(searchData.path, "*"); handle = UnsafeNativeMethods.FindFirstFileExW( searchPath, infoLevel, findData, NativeEnums.FindExSearchOp.NameMatch, IntPtr.Zero, additionalFlags); if (handle.IsInvalid) { handle.Dispose(); handle = null; state = STATE_FINISH; } else { state = STATE_INIT; if (FirstFileIncluded(findData)) { current = CreateFilePath(findData); } } }
/// <summary> /// Initializes this instance. /// </summary> private void Init() { WIN32_FIND_DATAW findData = new WIN32_FIND_DATAW(); string searchPath = Path.Combine(searchData.path, "*"); handle = UnsafeNativeMethods.FindFirstFileExW(searchPath, infoLevel, findData, NativeEnums.FindExSearchOp.NameMatch, IntPtr.Zero, additionalFlags); if (handle.IsInvalid) { int error = Marshal.GetLastWin32Error(); if (error != NativeConstants.ERROR_FILE_NOT_FOUND && error != NativeConstants.ERROR_NO_MORE_FILES) { HandleError(error); } else { // If no matching files are found exit when MoveNext is called. // This may happen for an empty root directory. state = STATE_FINISH; } } else { AddToVisitedDirectories(searchData.path); state = STATE_INIT; if (FirstFileIncluded(findData)) { current = CreateFilePath(findData); } } }
private void CommonInit() { Contract.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized"); // Execute searchCriteria against the current directory String searchPath = Path.InternalCombine(searchData.fullPath, searchCriteria); Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA(); // Open a Find handle #if MONO int error; _hnd = new SafeFindHandle(MonoIO.FindFirstFile(searchPath, out data.cFileName, out data.dwFileAttributes, out error)); #else _hnd = Win32Native.FindFirstFile(searchPath, data); #endif if (_hnd.IsInvalid) { #if MONO int hr = error; #else int hr = Marshal.GetLastWin32Error(); #endif if (hr != Win32Native.ERROR_FILE_NOT_FOUND && hr != Win32Native.ERROR_NO_MORE_FILES) { HandleError(hr, searchData.fullPath); } else { // flag this as empty only if we're searching just top directory // Used in fast path for top directory only empty = searchData.searchOption == SearchOption.TopDirectoryOnly; } } // fast path for TopDirectoryOnly. If we have a result, go ahead and set it to // current. If empty, dispose handle. if (searchData.searchOption == SearchOption.TopDirectoryOnly) { if (empty) { _hnd.Dispose(); } else { SearchResult searchResult = CreateSearchResult(searchData, data); if (_resultHandler.IsResultIncluded(searchResult)) { current = _resultHandler.CreateObject(searchResult); } } } // for AllDirectories, we first recurse into dirs, so cleanup and add searchData // to the stack else { _hnd.Dispose(); searchStack.Add(searchData); } }
internal Enumerator(string pattern, Mode mode) { this.pattern = pattern; this.current = null; this.hFindFile = null; this.mode = mode; }
/// <summary> /// Find the first match. /// </summary> /// <returns></returns> private bool FindFirst() { WIN32_FIND_DATA fd = new WIN32_FIND_DATA(); hFindFile = NativeMethods.FindFirstFile(pattern, fd); if (hFindFile.IsInvalid) { // Got an invalid find handle, get the error code int code = Marshal.GetLastWin32Error(); if (code == NativeMethods.ERROR_FILE_NOT_FOUND) { // file not found, just return false return(false); } // other errors, throw exception throw new Win32Exception(code); } if (!AttributesMatchMode(fd.dwFileAttributes)) { // if the file does not meet the match mode, // go find the next match. return(FindNext()); } current = fd.cFileName; return(true); }
/// <summary> /// Gets the directory nodes below the specified path /// </summary> /// <param name="path">The path.</param> /// <param name="canRead">if set to <c>true</c> [can read].</param> /// <returns></returns> public static IEnumerable <SccFileSystemNode> GetDirectoryNodes(string path, out bool canRead) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } string fullPath = path; if (!path.EndsWith("\\")) { path += "\\"; } fullPath = path + "*"; if (fullPath.Length > 240) { fullPath = SvnItem.MakeLongPath(fullPath); } NativeMethods.WIN32_FIND_DATA data; SafeFindHandle sh = NativeMethods.FindFirstFileW(fullPath, out data); if (sh.IsInvalid) { canRead = false; return(new SccFileSystemNode[0]); } else { canRead = true; return(DoGetDirectoryNodes(new SccFileSystemNode(path, data.cFileName, (FileAttributes)data.dwFileAttributes), sh)); } }
public static IEnumerable <string> EnumerateFolders(string root) { WIN32_FIND_DATA findData; string spec = Path.Combine(root, "*"); using (SafeFindHandle findHandle = FindFirstFile(spec, out findData)) { if (!findHandle.IsInvalid) { do { if ((findData.cFileName != ".") && (findData.cFileName != "..")) // Ignore special "." and ".." folders. { if ((findData.dwFileAttributes & FileAttributes.Directory) != 0) { yield return(Path.Combine(root, findData.cFileName)); } } }while (FindNextFile(findHandle, out findData)); } else { Debug.WriteLine("Cannot find files in " + spec, "Dmr.Common.IO.FileSystem.FolderContents()"); } } }
public static List <string> RecurseDirectory(string directory, int level) { var outList = new List <string>(); WIN32_FIND_DATA findData; // please note that the following line won't work if you try this on a network folder, like \\Machine\C$ // simply remove the \\?\ part in this case or use \\?\UNC\ prefix using (SafeFindHandle findHandle = FindFirstFile(@"\\?\" + directory + @"\*", out findData)) { if (!findHandle.IsInvalid) { do { if ((findData.dwFileAttributes & FileAttributes.Directory) != 0) { if (findData.cFileName != "." && findData.cFileName != "..") { string subdirectory = directory + (directory.EndsWith(@"\") ? "" : @"\") + findData.cFileName; if (level != 0) { outList.AddRange(RecurseDirectory(subdirectory, level - 1)); } } } else { // File outList.Add(directory + (directory.EndsWith(@"\") ? "" : @"\") + findData.cFileName); } }while (FindNextFile(findHandle, out findData)); } } return(outList); }
/// <summary> /// Finds the first directory in the given path. /// </summary> /// <param name="root">The path to search in.</param> /// <returns>The path to the first direcotry found.</returns> public static IEnumerable <string> EnumerateFolders(string root) { //We add an asterisk to make a wildcard search for all folders. string spec = Path.Combine(root, "*"); //We get the first file or directory in the provided path. using (SafeFindHandle findHandle = FindFirstFile(spec, out WIN32_FIND_DATA findData)) { if (!findHandle.IsInvalid) { do { // Ignore special "." and ".." folders. if ((findData.cFileName != ".") && (findData.cFileName != "..")) { //If it is a directory. if ((findData.dwFileAttributes & FileAttributes.Directory) != 0) { yield return(Path.Combine(root, findData.cFileName)); } } }while (FindNextFile(findHandle, out findData)); } } }
/// <summary> /// Get file attributes /// </summary> /// <param name="path">Path to file or folder</param> /// <param name="data">The file attribute structure to fill</param> /// <param name="tryagain">If false try get file attributes with GetFileAttributesEx function. If true try with the FindFirstFile function.</param> internal static void FillAttributeInfo(string path, ref WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain = false) { int num; if (tryagain) { WIN32_FIND_DATA win_find_data = new WIN32_FIND_DATA(); string fileName = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); int num2 = SafeNativeMethods.SetErrorMode(1); try { SafeFindHandle handle = SafeNativeMethods.FindFirstFile(fileName, win_find_data); try { if (handle.IsInvalid) { num = Marshal.GetLastWin32Error(); if (num != 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } } finally { handle.Close(); } } finally { _ = SafeNativeMethods.SetErrorMode(num2); } data.PopulateFrom(win_find_data); return; } bool flag2 = false; int newMode = SafeNativeMethods.SetErrorMode(1); try { flag2 = SafeNativeMethods.GetFileAttributesEx(path, 0, ref data); } finally { _ = SafeNativeMethods.SetErrorMode(newMode); } if (!flag2) { num = Marshal.GetLastWin32Error(); if (((num != 2) && (num != 3)) && (num != 0x15)) { FillAttributeInfo(path, ref data, true); //return; } //else if (num == 2) //return; //else if (num != 0) //throw new Win32Exception(num); //return; } }
public void Dispose() { if (hndFile != null) { hndFile.Dispose(); hndFile = null; } }
public void Dispose() { if (_hndFile != null) { _hndFile.Dispose(); _hndFile = null; } }
[System.Security.SecurityCritical] // auto-generated private void AddSearchableDirsToStack(Directory.SearchData localSearchData) { Contract.Requires(localSearchData != null); String searchPath = Path.Combine(localSearchData.fullPath, "*"); SafeFindHandle hnd = null; Interop.WIN32_FIND_DATA data = new Interop.WIN32_FIND_DATA(); try { // Get all files and dirs hnd = Interop.mincore.FindFirstFile(searchPath, ref data); if (hnd.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // This could happen if the dir doesn't contain any files. // Continue with the recursive search though, eventually // searchStack will become empty if (errorCode == Interop.ERROR_FILE_NOT_FOUND || errorCode == Interop.ERROR_NO_MORE_FILES || errorCode == Interop.ERROR_PATH_NOT_FOUND) { return; } HandleError(errorCode, localSearchData.fullPath); } // Add subdirs to searchStack. Exempt ReparsePoints as appropriate int incr = 0; do { if (Win32FileSystemEnumerableHelpers.IsDir(data)) { Contract.Assert(data.cFileName.Length != 0 && !Path.IsPathRooted(data.cFileName), "Expected file system enumeration to not have empty file/directory name and not have rooted name"); String tempFullPath = Path.Combine(localSearchData.fullPath, data.cFileName); String tempUserPath = Path.Combine(localSearchData.userPath, data.cFileName); SearchOption option = localSearchData.searchOption; // Setup search data for the sub directory and push it into the stack Directory.SearchData searchDataSubDir = new Directory.SearchData(tempFullPath, tempUserPath, option); _searchStack.Insert(incr++, searchDataSubDir); } } while (Interop.mincore.FindNextFile(hnd, ref data)); // We don't care about errors here } finally { if (hnd != null) { hnd.Dispose(); } } }
public void Reset() { if (null != hFindFile) { // close the find handle hFindFile.Close(); hFindFile = null; } }
private void CommonInit() { Debug.Assert(_searchCriteria != null, "searchCriteria should be initialized"); // Execute searchCriteria against the current directory PathHelpers.ThrowIfEmptyOrRootedPath(_searchCriteria); string searchPath = Path.Combine(_searchData.FullPath, _searchCriteria); Interop.Kernel32.WIN32_FIND_DATA data = new Interop.Kernel32.WIN32_FIND_DATA(); using (new DisableMediaInsertionPrompt()) { // Open a Find handle _hnd = Interop.Kernel32.FindFirstFile(searchPath, ref data); if (_hnd.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.Errors.ERROR_NO_MORE_FILES) { throw HandleError(errorCode, _searchData.FullPath); } else { // flag this as empty only if we're searching just top directory // Used in fast path for top directory only _empty = _searchOption == SearchOption.TopDirectoryOnly; } } } if (_searchOption == SearchOption.TopDirectoryOnly) { // fast path for TopDirectoryOnly. If we have a result, go ahead and set it to // current. If empty, dispose handle. if (_empty) { _hnd.Dispose(); } else { TSource result; if (IsResultIncluded(ref data, out result)) { current = result; } } } else { // for AllDirectories, we first recurse into dirs, so cleanup and add searchData // to the list _hnd.Dispose(); _searchList = new List <PathPair>(); _searchList.Add(_searchData); } }
/// <summary> /// Returns the find information. /// </summary> /// <param name="directoriesOnly">Attempts to filter to just directories where supported.</param> /// <param name="getAlternateName">Returns the alternate (short) file name in the FindResult.AlternateName field if it exists.</param> internal static FindResult FindFirstFile( string path, bool directoriesOnly = false, bool getAlternateName = false, bool returnNullIfNotFound = true) { if (Paths.EndsInDirectorySeparator(path)) { // Find first file does not like trailing separators so we'll cull it // // There is one weird special case. If we're passed a legacy root volume (e.g. C:\) then removing the // trailing separator will make the path drive relative, leading to whatever the current directory is // on that particular drive (randomness). (System32 for some odd reason in my tests.) // // You can't find a volume on it's own anyway, so we'll exit out in this case. For C: without a // trailing slash it is legitimate to try and find whatever that matches. Note that we also don't need // to bother checking the first character, as anything else there would be invalid. path = Paths.RemoveTrailingSeparators(path); if ((path.Length == 2 && path[1] == ':') || // C: (path.Length == 6 && path[5] == ':' && path.StartsWith(Paths.ExtendedPathPrefix))) // \\?\C: { if (returnNullIfNotFound) { return(null); } throw GetIoExceptionForError(WinError.ERROR_FILE_NOT_FOUND, path); } } path = Paths.AddExtendedPrefix(path); WIN32_FIND_DATA findData; SafeFindHandle handle = Private.FindFirstFileExW( path, getAlternateName ? FINDEX_INFO_LEVELS.FindExInfoStandard : FINDEX_INFO_LEVELS.FindExInfoBasic, out findData, // FINDEX_SEARCH_OPS.FindExSearchNameMatch is what FindFirstFile calls Ex wtih directoriesOnly ? FINDEX_SEARCH_OPS.FindExSearchLimitToDirectories :FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FIND_FIRST_EX_LARGE_FETCH); if (handle.IsInvalid) { int error = Marshal.GetLastWin32Error(); if (error == WinError.ERROR_FILE_NOT_FOUND && returnNullIfNotFound) { return(null); } throw GetIoExceptionForError(error, path); } return(new FindResult(handle, findData, Paths.GetDirectory(path))); }
public void Reset() { _findData = new WIN32_FIND_DATA(); if (_hndFile != null) { _hndFile.Dispose(); } new FileIOPermission(FileIOPermissionAccess.PathDiscovery, _currentFolderPath).Demand(); String searchPath = System.IO.Path.Combine(_currentFolderPath, _filter); _hndFile = FindFirstFileEx(searchPath, _infoLevel, _findData, _searchScope, null, _additionalFlags); }
private void CommonInit() { Contract.Assert(_searchCriteria != null && _searchData != null, "searchCriteria and searchData should be initialized"); // Execute searchCriteria against the current directory PathHelpers.ThrowIfEmptyOrRootedPath(_searchCriteria); String searchPath = Path.Combine(_searchData.fullPath, _searchCriteria); Interop.WIN32_FIND_DATA data = new Interop.WIN32_FIND_DATA(); // Open a Find handle _hnd = Interop.mincore.FindFirstFile(searchPath, ref data); if (_hnd.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.ERROR_FILE_NOT_FOUND && errorCode != Interop.ERROR_NO_MORE_FILES) { HandleError(errorCode, _searchData.fullPath); } else { // flag this as empty only if we're searching just top directory // Used in fast path for top directory only _empty = _searchData.searchOption == SearchOption.TopDirectoryOnly; } } // fast path for TopDirectoryOnly. If we have a result, go ahead and set it to // current. If empty, dispose handle. if (_searchData.searchOption == SearchOption.TopDirectoryOnly) { if (_empty) { _hnd.Dispose(); } else { SearchResult searchResult = CreateSearchResult(_searchData, data); if (_resultHandler.IsResultIncluded(searchResult)) { current = _resultHandler.CreateObject(searchResult); } } } // for AllDirectories, we first recurse into dirs, so cleanup and add searchData // to the stack else { _hnd.Dispose(); _searchStack.Add(_searchData); } }
internal FindResult(SafeFindHandle handle, WIN32_FIND_DATA findData, string basePath) { this.BasePath = basePath; this.FindHandle = handle; this.FileName = findData.cFileName; this.AlternateFileName = findData.cAlternateFileName; this.Attributes = (FileAttributes)findData.dwFileAttributes; this.Creation = GetDateTime(findData.ftCreationTime); this.LastAccess = GetDateTime(findData.ftLastAccessTime); this.LastWrite = GetDateTime(findData.ftLastWriteTime); this.Length = HighLowToLong(findData.nFileSizeHigh, findData.nFileSizeLow); }
private void AddSearchableDirsToStack(Directory.SearchData localSearchData) { string fileName = Path.InternalCombine(localSearchData.fullPath, "*"); SafeFindHandle hndFindFile = (SafeFindHandle)null; Win32Native.WIN32_FIND_DATA wiN32FindData = new Win32Native.WIN32_FIND_DATA(); try { hndFindFile = Win32Native.FindFirstFile(fileName, wiN32FindData); if (hndFindFile.IsInvalid) { int lastWin32Error = Marshal.GetLastWin32Error(); switch (lastWin32Error) { case 2: return; case 18: return; case 3: return; default: this.HandleError(lastWin32Error, localSearchData.fullPath); break; } } int num1 = 0; do { if (FileSystemEnumerableHelpers.IsDir(wiN32FindData)) { string fullPath = Path.InternalCombine(localSearchData.fullPath, wiN32FindData.cFileName); string str = Path.InternalCombine(localSearchData.userPath, wiN32FindData.cFileName); SearchOption searchOption = localSearchData.searchOption; string userPath = str; int num2 = (int)searchOption; Directory.SearchData searchData = new Directory.SearchData(fullPath, userPath, (SearchOption)num2); this.searchStack.Insert(num1++, searchData); } }while (Win32Native.FindNextFile(hndFindFile, wiN32FindData)); } finally { if (hndFindFile != null) { hndFindFile.Dispose(); } } }
internal static int FillAttributeInfo(string path, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, bool returnErrorOnNotFound) { int errorCode = Interop.Errors.ERROR_SUCCESS; // Neither GetFileAttributes or FindFirstFile like trailing separators path = path.TrimEnd(PathHelpers.DirectorySeparatorChars); using (new DisableMediaInsertionPrompt()) { if (!Interop.Kernel32.GetFileAttributesEx(path, Interop.Kernel32.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { // Files that are marked for deletion will not let you GetFileAttributes, // ERROR_ACCESS_DENIED is given back without filling out the data struct. // FindFirstFile, however, will. Historically we always gave back attributes // for marked-for-deletion files. var findData = new Interop.Kernel32.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(path, ref findData)) { if (handle.IsInvalid) { errorCode = Marshal.GetLastWin32Error(); } else { errorCode = Interop.Errors.ERROR_SUCCESS; data.PopulateFrom(ref findData); } } } } } if (errorCode != Interop.Errors.ERROR_SUCCESS && !returnErrorOnNotFound) { switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: case Interop.Errors.ERROR_PATH_NOT_FOUND: case Interop.Errors.ERROR_NOT_READY: // Removable media not ready // Return default value for backward compatibility data.fileAttributes = -1; return(Interop.Errors.ERROR_SUCCESS); } } return(errorCode); }
private static void GetFindData(string fullPath, bool isDirectory, ref Interop.Kernel32.WIN32_FIND_DATA findData) { using SafeFindHandle handle = Interop.Kernel32.FindFirstFile(Path.TrimEndingDirectorySeparator(fullPath), ref findData); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // File not found doesn't make much sense coming from a directory. if (isDirectory && errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) { errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } }
internal static bool IsSymbolicLink(string path) { var findData = new Interop.Kernel32.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(path, ref findData)) { if (!handle.IsInvalid) { return(((FileAttributes)findData.dwFileAttributes & FileAttributes.ReparsePoint) != 0 && (findData.dwReserved0 & 0xA000000C) != 0); // IO_REPARSE_TAG_SYMLINK } } return(false); }
private long RecurseDirectory(string directory, int level, out int files, out int folders) { IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); long size = 0; files = 0; folders = 0; WIN32_FIND_DATA findData; // please note that the following line won't work if you try this on a network folder, like \\Machine\C$ // simply remove the \\?\ part in this case or use \\?\UNC\ prefix using (SafeFindHandle findHandle = FindFirstFile(@"\\?\" + directory + @"\*", out findData)) { if (!findHandle.IsInvalid) { do { if ((findData.dwFileAttributes & FileAttributes.Directory) != 0) { if (findData.cFileName != "." && findData.cFileName != "..") { folders++; int subfiles, subfolders; string subdirectory = directory + (directory.EndsWith(@"\") ? "" : @"\") + findData.cFileName; if (level != 0) // allows -1 to do complete search. { size += RecurseDirectory(subdirectory, level - 1, out subfiles, out subfolders); folders += subfolders; files += subfiles; } } } else { // File files++; size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296; } }while (FindNextFile(findHandle, out findData)); } } return(size); }
internal static List <AlternateStreamData> GetStreams(string path) { if (path == null) { throw new ArgumentNullException("path"); } List <AlternateStreamData> list = new List <AlternateStreamData>(); AlternateStreamNativeData lpFindStreamData = new AlternateStreamNativeData(); SafeFindHandle hndFindFile = NativeMethods.FindFirstStreamW(path, NativeMethods.StreamInfoLevels.FindStreamInfoStandard, lpFindStreamData, 0); if (hndFindFile.IsInvalid) { throw new Win32Exception(); } try { do { AlternateStreamData data2; lpFindStreamData.Name = lpFindStreamData.Name.Substring(1); string b = ":$DATA"; if (!string.Equals(lpFindStreamData.Name, b, StringComparison.OrdinalIgnoreCase)) { lpFindStreamData.Name = lpFindStreamData.Name.Replace(b, ""); } data2 = new AlternateStreamData { Stream = lpFindStreamData.Name, Length = lpFindStreamData.Length, }; data2.FileName = path.Replace(data2.Stream, ""); data2.FileName = data2.FileName.Trim(new char[] { ':' }); list.Add(data2); lpFindStreamData = new AlternateStreamNativeData(); }while (NativeMethods.FindNextStreamW(hndFindFile, lpFindStreamData)); int error = Marshal.GetLastWin32Error(); if (error != 0x26) { throw new Win32Exception(error); } } finally { hndFindFile.Dispose(); } return(list); }
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); }
/// <summary> /// Returns a file (PathTooLong safe, volume guid safe). /// </summary> public static WIN32_FILE GetFile(string path) { WIN32_FIND_DATA data = new WIN32_FIND_DATA(); SafeFindHandle sfh = FindFirstFile(FixPathBackwards(path), data); if (sfh == null || sfh.IsInvalid || sfh.IsClosed) { throw new Exception(new Win32Exception(Marshal.GetLastWin32Error()).Message); } if (!sfh.IsInvalid && !sfh.IsClosed) { sfh.Close(); } sfh = null; return(new WIN32_FILE(path, data)); }
public static IEnumerable <LittleFileInfo> GetFiles(string folderPath) { WIN32_FIND_DATA win_find_data = new WIN32_FIND_DATA(); string prefixedfolderPath = folderPath.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); if (!prefixedfolderPath.StartsWith("\\\\", StringComparison.Ordinal)) { prefixedfolderPath = string.Concat("\\\\?\\", prefixedfolderPath); } int num2 = SafeNativeMethods.SetErrorMode(1); try { SafeFindHandle handle = SafeNativeMethods.FindFirstFile(prefixedfolderPath + @"\*", win_find_data); try { if (handle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } else { bool found = true; while (found) { if (win_find_data.cFileName != "." && win_find_data.cFileName != "..") { WIN32_FILE_ATTRIBUTE_DATA data = new WIN32_FILE_ATTRIBUTE_DATA(); data.PopulateFrom(win_find_data); yield return(new LittleFileInfo(folderPath, win_find_data.cFileName, data)); } found = SafeNativeMethods.FindNextFile(handle, win_find_data); } } } finally { handle.Close(); } } finally { _ = SafeNativeMethods.SetErrorMode(num2); } }
private void CommonInit() { string fileName = Path.InternalCombine(this.searchData.fullPath, this.searchCriteria); Win32Native.WIN32_FIND_DATA wiN32FindData = new Win32Native.WIN32_FIND_DATA(); this._hnd = Win32Native.FindFirstFile(fileName, wiN32FindData); if (this._hnd.IsInvalid) { int lastWin32Error = Marshal.GetLastWin32Error(); switch (lastWin32Error) { case 2: case 18: this.empty = this.searchData.searchOption == SearchOption.TopDirectoryOnly; break; default: this.HandleError(lastWin32Error, this.searchData.fullPath); break; } } if (this.searchData.searchOption == SearchOption.TopDirectoryOnly) { if (this.empty) { this._hnd.Dispose(); } else { SearchResult searchResult = this.CreateSearchResult(this.searchData, wiN32FindData); if (!this._resultHandler.IsResultIncluded(searchResult)) { return; } this.current = this._resultHandler.CreateObject(searchResult); } } else { this._hnd.Dispose(); this.searchStack.Add(this.searchData); } }
private bool ShouldUseWinRT(string fullPath, bool isCreate) { bool useWinRt = false; do { Interop.WIN32_FIND_DATA findData = new Interop.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.mincore.FindFirstFile(fullPath, ref findData)) { int error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) { if (error == Interop.ERROR_ACCESS_DENIED) { // The path was not accessible with Win32, so try WinRT useWinRt = true; break; } else if (error != Interop.ERROR_PATH_NOT_FOUND && error != Interop.ERROR_FILE_NOT_FOUND) { // We hit some error other than ACCESS_DENIED or NOT_FOUND, // Default to Win32 to provide most accurate error behavior break; } } else { // Use WinRT for placeholder files useWinRt = IsPlaceholderFile(findData); break; } } // error was ERROR_PATH_NOT_FOUND or ERROR_FILE_NOT_FOUND // if we are creating a file/directory we cannot assume that Win32 will have access to // the parent directory, so we walk up the path. fullPath = PathHelpers.GetDirectoryNameInternal(fullPath); // only walk up the path if we are creating a file/directory and not at the root } while (isCreate && !String.IsNullOrEmpty(fullPath)); return(useWinRt); }
public static extern bool FindNextFileW(SafeFindHandle hndFindFile, [In, Out, MarshalAs(UnmanagedType.LPStruct)] WIN32_FIND_DATAW lpFindFileData);
public static extern bool FindNextFile( /* [in] */ SafeFindHandle findFile, /* [out] */ out Win32FindData findFileData);
internal static extern bool FindNextFile(SafeFindHandle hndFindFile, [In, Out, MarshalAs(UnmanagedType.LPStruct)] FindData lpFindFileData);
internal static extern bool FindNextFile(SafeFindHandle hFindFile, out WIN32_FIND_DATA lpFindFileData);
public static extern bool FindNextFile(SafeFindHandle hFindFile, [In, Out] FindData lpFindFileData);