예제 #1
0
        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);
            }
        }
예제 #2
0
 public void Dispose()
 {
     if (_hndFile != null)
     {
         _hndFile.Dispose();
         _hndFile = null;
     }
 }
예제 #3
0
 public void Dispose()
 {
     if (hndFile != null)
     {
         hndFile.Dispose();
         hndFile = null;
     }
 }
예제 #4
0
        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);
            }
        }
예제 #5
0
        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);
            }
        }
        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);
                }
            }
        }
예제 #7
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing,
 /// or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     if (!m_hndFindFile.IsClosed)
     {
         m_hndFindFile.Dispose();
     }
 }
예제 #8
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing,
 /// or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     if (m_hndFindFile != null)
     {
         m_hndFindFile.Dispose();
     }
 }
예제 #9
0
        [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();
                }
            }
        }
예제 #10
0
 protected override void Dispose(bool disposing)
 {
     try
     {
         _hnd?.Dispose();
     }
     finally
     {
         base.Dispose(disposing);
     }
 }
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (!disposed)
            {
                disposed = true;

                if (handle != null)
                {
                    handle.Dispose();
                    handle = null;
                }

                if (shellLink != null)
                {
                    shellLink.Dispose();
                    shellLink = null;
                }
                current = null;
                state = -1;
                SetErrorModeWrapper(oldErrorMode);
            }
        }
예제 #12
0
        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();
                }
            }
        }
예제 #13
0
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (_hnd != null)
         {
             _hnd.Dispose();
         }
     }
     finally
     {
         Win32Native.SetErrorMode(oldMode);
         base.Dispose(disposing);
     }
 }
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (_hnd != null)
         {
             _hnd.Dispose();
         }
     }
     finally
     {
         Interop.mincore.SetErrorMode(_oldMode);
         base.Dispose(disposing);
     }
 }
예제 #15
0
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (_hnd != null)
                {
                    _hnd.Dispose();
                }
            }
            finally
            {
#if !MONO  // TODO: check if we need this on Windows
                Win32Native.SetErrorMode(oldMode);
#endif
                base.Dispose(disposing);
            }
        }
예제 #16
0
        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);
        }
예제 #17
0
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (_hnd != null)
         {
             _hnd.Dispose();
         }
     }
     finally
     {
         if (_setBackOldMode)
         {
             uint _ignore;
             Interop.Kernel32.SetThreadErrorMode(_oldMode, out _ignore);
         }
         base.Dispose(disposing);
     }
 }
        private void AddSearchableDirsToStack(Directory.SearchData localSearchData)
        {
            string         fileName       = Path.InternalCombine(localSearchData.fullPath, "*");
            SafeFindHandle safeFindHandle = null;

            Win32Native.WIN32_FIND_DATA win32_FIND_DATA = default(Win32Native.WIN32_FIND_DATA);
            try
            {
                safeFindHandle = Win32Native.FindFirstFile(fileName, ref win32_FIND_DATA);
                if (safeFindHandle.IsInvalid)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    if (lastWin32Error == 2 || lastWin32Error == 18 || lastWin32Error == 3)
                    {
                        return;
                    }
                    this.HandleError(lastWin32Error, localSearchData.fullPath);
                }
                int num = 0;
                do
                {
                    if (win32_FIND_DATA.IsNormalDirectory)
                    {
                        string               cFileName    = win32_FIND_DATA.cFileName;
                        string               text         = Path.CombineNoChecks(localSearchData.fullPath, cFileName);
                        string               text2        = Path.CombineNoChecks(localSearchData.userPath, cFileName);
                        SearchOption         searchOption = localSearchData.searchOption;
                        Directory.SearchData item         = new Directory.SearchData(text, text2, searchOption);
                        this.searchStack.Insert(num++, item);
                    }
                }while (Win32Native.FindNextFile(safeFindHandle, ref win32_FIND_DATA));
            }
            finally
            {
                if (safeFindHandle != null)
                {
                    safeFindHandle.Dispose();
                }
            }
        }
예제 #19
0
        [System.Security.SecurityCritical]  // auto-generated
        private void AddSearchableDirsToStack(Directory.SearchData localSearchData)
        {
            Contract.Requires(localSearchData != null);

            String         searchPath = Path.InternalCombine(localSearchData.fullPath, "*");
            SafeFindHandle hnd        = null;

            Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
            try
            {
                // Get all files and dirs
                hnd = Win32Native.FindFirstFile(searchPath, data);

                if (hnd.IsInvalid)
                {
                    int hr = 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 (hr == Win32Native.ERROR_FILE_NOT_FOUND || hr == Win32Native.ERROR_NO_MORE_FILES || hr == Win32Native.ERROR_PATH_NOT_FOUND)
                    {
                        return;
                    }

                    HandleError(hr, localSearchData.fullPath);
                }

                // Add subdirs to searchStack. Exempt ReparsePoints as appropriate
                int incr = 0;
                do
                {
                    if (FileSystemEnumerableHelpers.IsDir(data))
                    {
                        String tempFullPath = Path.InternalCombine(localSearchData.fullPath, data.cFileName);
                        String tempUserPath = Path.InternalCombine(localSearchData.userPath, data.cFileName);

                        SearchOption option = localSearchData.searchOption;

#if EXCLUDE_REPARSEPOINTS
                        // Traverse reparse points depending on the searchoption specified
                        if ((searchDataSubDir.searchOption == SearchOption.AllDirectories) && (0 != (data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_REPARSE_POINT)))
                        {
                            option = SearchOption.TopDirectoryOnly;
                        }
#endif
                        // 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 (Win32Native.FindNextFile(hnd, data));
                // We don't care about errors here
            }
            finally
            {
                if (hnd != null)
                {
                    hnd.Dispose();
                }
            }
        }
예제 #20
0
        public override bool MoveNext()
        {
            Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
            switch (state)
            {
            case STATE_INIT:
            {
                if (empty)
                {
                    state = STATE_FINISH;
                    goto case STATE_FINISH;
                }
                if (searchData.searchOption == SearchOption.TopDirectoryOnly)
                {
                    state = STATE_FIND_NEXT_FILE;
                    if (current != null)
                    {
                        return(true);
                    }
                    else
                    {
                        goto case STATE_FIND_NEXT_FILE;
                    }
                }
                else
                {
                    state = STATE_SEARCH_NEXT_DIR;
                    goto case STATE_SEARCH_NEXT_DIR;
                }
            }

            case STATE_SEARCH_NEXT_DIR:
            {
                Contract.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
                // Traverse directory structure. We need to get '*'
                while (searchStack.Count > 0)
                {
                    searchData = searchStack[0];
                    Contract.Assert((searchData.fullPath != null), "fullpath can't be null!");
                    searchStack.RemoveAt(0);

                    // Traverse the subdirs
                    AddSearchableDirsToStack(searchData);

                    // Execute searchCriteria against the current directory
                    String searchPath = Path.InternalCombine(searchData.fullPath, searchCriteria);

                    // Open a Find handle
                    _hnd = Win32Native.FindFirstFile(searchPath, data);
                    if (_hnd.IsInvalid)
                    {
                        int hr = Marshal.GetLastWin32Error();
                        if (hr == Win32Native.ERROR_FILE_NOT_FOUND || hr == Win32Native.ERROR_NO_MORE_FILES || hr == Win32Native.ERROR_PATH_NOT_FOUND)
                        {
                            continue;
                        }

                        _hnd.Dispose();
                        HandleError(hr, searchData.fullPath);
                    }

                    state = STATE_FIND_NEXT_FILE;
                    needsParentPathDiscoveryDemand = true;
                    SearchResult searchResult = CreateSearchResult(searchData, data);
                    if (_resultHandler.IsResultIncluded(searchResult))
                    {
                        if (needsParentPathDiscoveryDemand)
                        {
                            DoDemand(searchData.fullPath);
                            needsParentPathDiscoveryDemand = false;
                        }
                        current = _resultHandler.CreateObject(searchResult);
                        return(true);
                    }
                    else
                    {
                        goto case STATE_FIND_NEXT_FILE;
                    }
                }
                state = STATE_FINISH;
                goto case STATE_FINISH;
            }

            case STATE_FIND_NEXT_FILE:
            {
                if (searchData != null && _hnd != null)
                {
                    // Keep asking for more matching files/dirs, add it to the list
                    while (Win32Native.FindNextFile(_hnd, data))
                    {
                        SearchResult searchResult = CreateSearchResult(searchData, data);
                        if (_resultHandler.IsResultIncluded(searchResult))
                        {
                            if (needsParentPathDiscoveryDemand)
                            {
                                DoDemand(searchData.fullPath);
                                needsParentPathDiscoveryDemand = false;
                            }
                            current = _resultHandler.CreateObject(searchResult);
                            return(true);
                        }
                    }

                    // Make sure we quit with a sensible error.
                    int hr = Marshal.GetLastWin32Error();

                    if (_hnd != null)
                    {
                        _hnd.Dispose();
                    }

                    // ERROR_FILE_NOT_FOUND is valid here because if the top level
                    // dir doen't contain any subdirs and matching files then
                    // we will get here with this errorcode from the searchStack walk
                    if ((hr != 0) && (hr != Win32Native.ERROR_NO_MORE_FILES) &&
                        (hr != Win32Native.ERROR_FILE_NOT_FOUND))
                    {
                        HandleError(hr, searchData.fullPath);
                    }
                }
                if (searchData.searchOption == SearchOption.TopDirectoryOnly)
                {
                    state = STATE_FINISH;
                    goto case STATE_FINISH;
                }
                else
                {
                    state = STATE_SEARCH_NEXT_DIR;
                    goto case STATE_SEARCH_NEXT_DIR;
                }
            }

            case STATE_FINISH:
            {
                Dispose();
                break;
            }
            }
            return(false);
        }
        [SecurityCritical]  // auto-generated
        private void AddSearchableDirsToList(PathPair localSearchData)
        {
            string         searchPath = Path.Combine(localSearchData.FullPath, "*");
            SafeFindHandle hnd        = null;

            Interop.mincore.WIN32_FIND_DATA data = new Interop.mincore.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
                    // _searchList will become empty
                    if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.mincore.Errors.ERROR_NO_MORE_FILES || errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)
                    {
                        return;
                    }

                    HandleError(errorCode, localSearchData.FullPath);
                }

                // Add subdirs to _searchList. Exempt ReparsePoints as appropriate
                int initialCount = _searchList.Count;
                do
                {
                    if (Win32FileSystemEnumerableHelpers.IsDir(ref data))
                    {
                        Debug.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);

                        // Setup search data for the sub directory and push it into the list
                        PathPair searchDataSubDir = new PathPair(tempUserPath, tempFullPath);

                        Debug.Assert(_searchList != null, "_searchList should not be null");
                        _searchList.Add(searchDataSubDir);
                    }
                } while (Interop.mincore.FindNextFile(hnd, ref data));

                // Reverse the items just added to maintain FIFO order
                if (_searchList.Count > initialCount)
                {
                    _searchList.Reverse(initialCount, _searchList.Count - initialCount);
                }

                // We don't care about errors here
            }
            finally
            {
                if (hnd != null)
                {
                    hnd.Dispose();
                }
            }
        }
        public override bool MoveNext()
        {
            Interop.mincore.WIN32_FIND_DATA data = new Interop.mincore.WIN32_FIND_DATA();
            switch (state)
            {
            case STATE_INIT:
            {
                if (_empty)
                {
                    state = STATE_FINISH;
                    goto case STATE_FINISH;
                }
                if (_searchOption == SearchOption.TopDirectoryOnly)
                {
                    state = STATE_FIND_NEXT_FILE;
                    if (current != null)
                    {
                        return(true);
                    }
                    else
                    {
                        goto case STATE_FIND_NEXT_FILE;
                    }
                }
                else
                {
                    state = STATE_SEARCH_NEXT_DIR;
                    goto case STATE_SEARCH_NEXT_DIR;
                }
            }

            case STATE_SEARCH_NEXT_DIR:
            {
                Debug.Assert(_searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
                Debug.Assert(_searchList != null, "_searchList should not be null");
                // Traverse directory structure. We need to get '*'
                while (_searchList.Count > 0)
                {
                    int index = _searchList.Count - 1;
                    _searchData = _searchList[index];
                    Debug.Assert((_searchData.FullPath != null), "fullpath can't be null!");
                    _searchList.RemoveAt(index);

                    // Traverse the subdirs
                    AddSearchableDirsToList(_searchData);

                    // Execute searchCriteria against the current directory
                    string searchPath = Path.Combine(_searchData.FullPath, _searchCriteria);

                    // Open a Find handle
                    _hnd = Interop.mincore.FindFirstFile(searchPath, ref data);
                    if (_hnd.IsInvalid)
                    {
                        int errorCode = Marshal.GetLastWin32Error();
                        if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.mincore.Errors.ERROR_NO_MORE_FILES || errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND)
                        {
                            continue;
                        }

                        _hnd.Dispose();
                        HandleError(errorCode, _searchData.FullPath);
                    }

                    state = STATE_FIND_NEXT_FILE;

                    TSource result;
                    if (IsResultIncluded(ref data, out result))
                    {
                        current = result;
                        return(true);
                    }
                    else
                    {
                        goto case STATE_FIND_NEXT_FILE;
                    }
                }
                state = STATE_FINISH;
                goto case STATE_FINISH;
            }

            case STATE_FIND_NEXT_FILE:
            {
                if (_hnd != null)
                {
                    // Keep asking for more matching files/dirs, add it to the list
                    while (Interop.mincore.FindNextFile(_hnd, ref data))
                    {
                        TSource result;
                        if (IsResultIncluded(ref data, out result))
                        {
                            current = result;
                            return(true);
                        }
                    }

                    // Make sure we quit with a sensible error.
                    int errorCode = Marshal.GetLastWin32Error();

                    if (_hnd != null)
                    {
                        _hnd.Dispose();
                    }

                    // ERROR_FILE_NOT_FOUND is valid here because if the top level
                    // dir doesn't contain any subdirs and matching files then
                    // we will get here with this errorcode from the _searchList walk
                    if ((errorCode != 0) && (errorCode != Interop.mincore.Errors.ERROR_NO_MORE_FILES) &&
                        (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND))
                    {
                        HandleError(errorCode, _searchData.FullPath);
                    }
                }
                if (_searchOption == SearchOption.TopDirectoryOnly)
                {
                    state = STATE_FINISH;
                    goto case STATE_FINISH;
                }
                else
                {
                    state = STATE_SEARCH_NEXT_DIR;
                    goto case STATE_SEARCH_NEXT_DIR;
                }
            }

            case STATE_FINISH:
            {
                Dispose();
                break;
            }
            }
            return(false);
        }
예제 #23
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing,
 /// or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     _mHndFindFile?.Dispose();
 }
예제 #24
0
        public static IEnumerable <DirEntry> Entries(string startDir, Action <int, string> DirErrorHandler, int maxDepth, Predicate <string> EnterDir, bool FollowJunctions)
        {
            // expand directory to "unicode" convention
            StringBuilder            dir           = new StringBuilder(Long.GetLongFilenameNotation(startDir));
            int                      baseDirLength = dir.Length;
            SafeFindHandle           SearchHandle  = null;
            Stack <Internal_DirInfo> dirStack      = new Stack <Internal_DirInfo>();
            int                      depth         = 0;

            Spi.Native.Win32.WIN32_FIND_DATA find_data;

            bool findFirstFile = true;

            do
            {
                if (findFirstFile)
                {
                    findFirstFile = false;

                    dir.Append("\\*");
                    SearchHandle = Win32.FindFirstFile(dir.ToString(), out find_data);
                    dir.Length  -= 2;   // remove \* added before
                    if (SearchHandle.IsInvalid)
                    {
                        if (DirErrorHandler != null)
                        {
                            DirErrorHandler(Marshal.GetLastWin32Error(), dir.ToString());
                        }
                        StepBack(ref dir, ref dirStack, out SearchHandle, ref depth);
                        continue;
                    }
                }
                else
                {
                    if (!Spi.Native.Win32.FindNextFile(SearchHandle, out find_data))
                    {
                        SearchHandle.Dispose();
                        StepBack(ref dir, ref dirStack, out SearchHandle, ref depth);
                        continue;
                    }
                }
                if (IsDirectoryFlagSet(find_data.dwFileAttributes))  // is a dir
                {
                    if (IsDotOrDotDotDirectory(find_data.cFileName))
                    {
                        continue;
                    }
                    if (WalkIntoDir(ref find_data, EnterDir, FollowJunctions))
                    {
                        yield return(new DirEntry(dir, find_data, baseDirLength));

                        //
                        // go down if depth is ok
                        //
                        if (maxDepth == -1 || depth < maxDepth)
                        {
                            depth++;
                            dirStack.Push(new Internal_DirInfo()
                            {
                                DirnameLength = find_data.cFileName.Length, handle = SearchHandle
                            });
                            dir.Append("\\").Append(find_data.cFileName);
                            findFirstFile = true;
                        }
                    }
                }
                else
                {
                    yield return(new DirEntry(dir, find_data, baseDirLength));
                }
            } while (SearchHandle != null);
        }
        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>
        /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
        /// </returns>
        public bool MoveNext()
        {
            WIN32_FIND_DATAW findData = new WIN32_FIND_DATAW();

            switch (state)
            {
                case STATE_INIT:
                    state = STATE_FIND_FILES;

                    if (current != null)
                    {
                        return true;
                    }
                    else
                    {
                        goto case STATE_FIND_FILES;
                    }
                case STATE_FIND_FILES:
                    do
                    {
                        if (handle == null)
                        {
                            searchData = searchDirectories.Dequeue();

                            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;

                                if (searchDirectories.Count > 0)
                                {
                                    continue;
                                }
                                else
                                {
                                    state = STATE_FINISH;
                                    goto case STATE_FINISH;
                                }
                            }

                            needPathDiscoveryDemand = true;
                            if (FirstFileIncluded(findData))
                            {
                                current = CreateFilePath(findData);
                                return true;
                            }
                        }

                        while (UnsafeNativeMethods.FindNextFileW(handle, findData))
                        {
                            if ((findData.dwFileAttributes & NativeConstants.FILE_ATTRIBUTE_DIRECTORY) == 0)
                            {
                                if (IsFileIncluded(findData))
                                {
                                    current = CreateFilePath(findData);
                                    return true;
                                }
                            }
                            else if (searchOption == SearchOption.AllDirectories && !findData.cFileName.Equals(".") && !findData.cFileName.Equals(".."))
                            {
                                searchDirectories.Enqueue(new SearchData(searchData, findData.cFileName));
                            }
                        }

                        handle.Dispose();
                        handle = null;

                    } while (searchDirectories.Count > 0);

                    state = STATE_FINISH;
                    goto case STATE_FINISH;
                case STATE_FINISH:
                    Dispose();
                    break;
            }

            return false;
        }
예제 #26
0
        /// <summary>
        /// Gets the files.
        /// </summary>
        /// <param name="dir">The dir.</param>
        /// <param name="pattern">The pattern.</param>
        /// <param name="searchOption">The search option.</param>
        /// <returns></returns>
        public static IEnumerable <FileInfo> GetFiles(DirectoryInfo dir, string pattern, SearchOption searchOption)
        {
            // We suppressed this demand for each p/invoke call, so demand it upfront once
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            // Validate parameters
            if (dir == null)
            {
                throw new ArgumentNullException("dir");
            }
            if (pattern == null)
            {
                throw new ArgumentNullException("pattern");
            }

            // Setup
            WIN32_FIND_DATA       findData    = new WIN32_FIND_DATA();
            Stack <DirectoryInfo> directories = new Stack <DirectoryInfo>();

            directories.Push(dir);

            // Process each directory
            ErrorModes origErrorMode = SetErrorMode(ErrorModes.FailCriticalErrors);

            try
            {
                while (directories.Count > 0)
                {
                    // Get the name of the next directory and the corresponding search pattern
                    dir = directories.Pop();
                    string dirPath = dir.FullName.Trim();
                    if (dirPath.Length == 0)
                    {
                        continue;
                    }
                    char lastChar = dirPath[dirPath.Length - 1];
                    if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
                    {
                        dirPath += Path.DirectorySeparatorChar;
                    }

                    // Process all files in that directory
                    SafeFindHandle handle = FindFirstFile(dirPath + pattern, findData);
                    if (handle.IsInvalid)
                    {
                        int error = Marshal.GetLastWin32Error();
                        if (error == ERROR_ACCESS_DENIED)
                        {
                            continue;
                        }
                        else if (error != ERROR_FILE_NOT_FOUND)
                        {
                            throw new Win32Exception(error);
                        }
                    }
                    else
                    {
                        try
                        {
                            do
                            {
                                if ((findData.dwFileAttributes & FileAttributes.Directory) == 0)
                                {
                                    yield return(new FileInfo(dirPath + findData.cFileName));
                                }
                            }while (FindNextFile(handle, findData));
                            int error = Marshal.GetLastWin32Error();
                            if (error != ERROR_NO_MORE_FILES)
                            {
                                throw new Win32Exception(error);
                            }
                        }
                        finally { handle.Dispose(); }
                    }

                    // Add all child directories if that's what the user wants
                    if (searchOption == SearchOption.AllDirectories)
                    {
                        foreach (DirectoryInfo childDir in dir.GetDirectories())
                        {
                            if ((File.GetAttributes(childDir.FullName) & FileAttributes.ReparsePoint) == 0)
                            {
                                directories.Push(childDir);
                            }
                        }
                    }
                }
            }
            finally { SetErrorMode(origErrorMode); }
        }
예제 #27
0
        public static IEnumerable <FileSystemInfo> GetFileSystemInfos(DirectoryInfo dir, string pattern, SearchOption searchOption, bool includeDirectories, bool includeFiles)
        {
            // We suppressed this demand for each p/invoke call, so demand it upfront once
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            // Validate parameters
            if (dir == null)
            {
                throw new ArgumentNullException("dir");
            }
            if (pattern == null)
            {
                throw new ArgumentNullException("pattern");
            }

            // Setup
            WIN32_FIND_DATA       findData    = new WIN32_FIND_DATA();
            Stack <DirectoryInfo> directories = new Stack <DirectoryInfo>();

            directories.Push(dir);

            // Process each directory
            ErrorModes origErrorMode = SetErrorMode(ErrorModes.FailCriticalErrors);

            try
            {
                while (directories.Count > 0)
                {
                    // Get the name of the next directory and the corresponding search pattern
                    dir = directories.Pop();
                    string dirPath = dir.FullName.Trim();
                    if (dirPath.Length == 0)
                    {
                        continue;
                    }
                    char lastChar = dirPath[dirPath.Length - 1];
                    if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
                    {
                        dirPath += Path.DirectorySeparatorChar;
                    }

                    // Process all files in that directory
                    SafeFindHandle handle = FindFirstFile(dirPath + pattern, findData);
                    if (handle.IsInvalid)
                    {
                        int error = Marshal.GetLastWin32Error();
                        if (error == ERROR_ACCESS_DENIED ||
                            error == ERROR_FILE_NOT_FOUND)
                        {
                            continue;
                        }
                        else
                        {
                            throw new Win32Exception(error);
                        }
                    }
                    else
                    {
                        try
                        {
                            do
                            {
                                if ((findData.dwFileAttributes & FileAttributes.Directory) == 0)
                                {
                                    if (includeFiles)
                                    {
                                        yield return(new FileInfo(dirPath + findData.cFileName));
                                    }
                                }
                                else
                                {
                                    if (includeDirectories && findData.cFileName != "." && findData.cFileName != "..")
                                    {
                                        yield return(new DirectoryInfo(dirPath + findData.cFileName));
                                    }
                                }
                            }while (FindNextFile(handle, findData));
                            int error = Marshal.GetLastWin32Error();
                            if (error != ERROR_NO_MORE_FILES)
                            {
                                throw new Win32Exception(error);
                            }
                        }
                        finally { handle.Dispose(); }
                    }

                    // Add all child directories if that's what the user wants
                    if (searchOption == SearchOption.AllDirectories)
                    {
                        try
                        {
                            foreach (DirectoryInfo childDir in GetDirectories(dir, "*", SearchOption.TopDirectoryOnly))                             //Top only, as we're all ready handling recursion here.
                            {
                                try
                                {
                                    if ((File.GetAttributes(childDir.FullName) & FileAttributes.ReparsePoint) == 0)
                                    {
                                        directories.Push(childDir);
                                    }
                                }
                                catch (Exception childDirEx)
                                {
                                    //Can't get subfolders
                                    System.Diagnostics.Trace.WriteLine("Can't search inside: " + childDir.Name);
                                    System.Diagnostics.Trace.Indent();
                                    System.Diagnostics.Trace.WriteLine(childDirEx.Message);
                                    System.Diagnostics.Trace.Unindent();
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            //Can't get subfolders
                            System.Diagnostics.Trace.WriteLine("Can't search inside: " + dirPath);
                            System.Diagnostics.Trace.Indent();
                            System.Diagnostics.Trace.WriteLine(e.Message);
                            System.Diagnostics.Trace.Unindent();
                        }
                    }
                }
            }
            finally { SetErrorMode(origErrorMode); }
        }
예제 #28
0
 /// <summary>
 ///     Performs application-defined tasks associated with freeing, releasing,
 ///     or resetting unmanaged resources.
 /// </summary>
 public void Dispose() => _hndFindFile?.Dispose();
예제 #29
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static int FillAttributeInfo(String path, ref Interop.mincore.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
        {
            int errorCode = 0;

            if (tryagain) // someone has a handle to the file open, or other error
            {
                Interop.mincore.WIN32_FIND_DATA findData;
                findData = new Interop.mincore.WIN32_FIND_DATA();

                // Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
                String tempPath = path.TrimEnd(PathHelpers.DirectorySeparatorChars);

                // For floppy drives, normally the OS will pop up a dialog saying
                // there is no disk in drive A:, please insert one.  We don't want that.
                // SetErrorMode will let us disable this, but we should set the error
                // mode back, since this may have wide-ranging effects.
                uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
                try
                {
                    bool           error  = false;
                    SafeFindHandle handle = Interop.mincore.FindFirstFile(tempPath, ref findData);
                    try
                    {
                        if (handle.IsInvalid)
                        {
                            error     = true;
                            errorCode = Marshal.GetLastWin32Error();

                            if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND ||
                                errorCode == Interop.mincore.Errors.ERROR_PATH_NOT_FOUND ||
                                errorCode == Interop.mincore.Errors.ERROR_NOT_READY)  // floppy device not ready
                            {
                                if (!returnErrorOnNotFound)
                                {
                                    // Return default value for backward compatibility
                                    errorCode           = 0;
                                    data.fileAttributes = -1;
                                }
                            }
                            return(errorCode);
                        }
                    }
                    finally
                    {
                        // Close the Win32 handle
                        try
                        {
                            handle.Dispose();
                        }
                        catch
                        {
                            // if we're already returning an error, don't throw another one.
                            if (!error)
                            {
                                throw Win32Marshal.GetExceptionForLastWin32Error();
                            }
                        }
                    }
                }
                finally
                {
                    Interop.mincore.SetErrorMode(oldMode);
                }

                // Copy the information to data
                data.PopulateFrom(ref findData);
            }
            else
            {
                // For floppy drives, normally the OS will pop up a dialog saying
                // there is no disk in drive A:, please insert one.  We don't want that.
                // SetErrorMode will let us disable this, but we should set the error
                // mode back, since this may have wide-ranging effects.
                bool success = false;
                uint oldMode = Interop.mincore.SetErrorMode(Interop.mincore.SEM_FAILCRITICALERRORS);
                try
                {
                    success = Interop.mincore.GetFileAttributesEx(path, Interop.mincore.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data);
                }
                finally
                {
                    Interop.mincore.SetErrorMode(oldMode);
                }

                if (!success)
                {
                    errorCode = Marshal.GetLastWin32Error();
                    if (errorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND &&
                        errorCode != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND &&
                        errorCode != Interop.mincore.Errors.ERROR_NOT_READY)  // floppy device not ready
                    {
                        // In case someone latched onto the file. Take the perf hit only for failure
                        return(FillAttributeInfo(path, ref data, true, returnErrorOnNotFound));
                    }
                    else
                    {
                        if (!returnErrorOnNotFound)
                        {
                            // Return default value for backward compatibility
                            errorCode           = 0;
                            data.fileAttributes = -1;
                        }
                    }
                }
            }

            return(errorCode);
        }
예제 #30
0
        static internal IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(string basePath, string searchPattern, SearchOption searchOption)
        {
            Path.Validate(basePath);

            SafeFindHandle findHandle = null;

            try {
                string filePath;
                int    nativeAttrs;

                string basePathWithPattern = Path.Combine(basePath, searchPattern);

                int nativeError;
                try {} finally {
                    findHandle = new SafeFindHandle(MonoIO.FindFirstFile(basePathWithPattern, out filePath, out nativeAttrs, out nativeError));
                }

                if (findHandle.IsInvalid)
                {
                    MonoIOError error = (MonoIOError)nativeError;
                    if (error != MonoIOError.ERROR_FILE_NOT_FOUND)
                    {
                        throw MonoIO.GetException(Path.GetDirectoryName(basePathWithPattern), error);
                    }

                    yield break;
                }

                do
                {
                    if (filePath == null)
                    {
                        yield break;
                    }

                    if (filePath == "." || filePath == "..")
                    {
                        continue;
                    }

                    FileAttributes attrs = (FileAttributes)nativeAttrs;

                    string fullPath = Path.Combine(basePath, filePath);

                    if ((attrs & FileAttributes.ReparsePoint) == 0)
                    {
                        if ((attrs & FileAttributes.Directory) != 0)
                        {
                            yield return(new DirectoryInfo(fullPath));
                        }
                        else
                        {
                            yield return(new FileInfo(fullPath));
                        }
                    }

                    if ((attrs & FileAttributes.Directory) != 0 && searchOption == SearchOption.AllDirectories)
                    {
                        foreach (FileSystemInfo child in EnumerateFileSystemInfos(fullPath, searchPattern, searchOption))
                        {
                            yield return(child);
                        }
                    }
                } while (MonoIO.FindNextFile(findHandle.DangerousGetHandle(), out filePath, out nativeAttrs, out int _));
            } finally {
                if (findHandle != null)
                {
                    findHandle.Dispose();
                }
            }
        }