/// <summary> /// Searches for the file whose name is given by <see cref="fileName"/> recursively starting with the folder <see cref="rootDir"/>. /// </summary> /// <param name="fileName">Name of the file you want to find.</param> /// <param name="rootDir">Path to the directory where you want to start the search.</param> /// <returns>Full path to the first copy of the file whose name matches <see cref="fileName"/>; blank string if not found.</returns> public static string FindFile(string fileName, string rootDir = @"C:\") { if (string.IsNullOrWhiteSpace(fileName)) { return(string.Empty); } if (!Directory.Exists(rootDir)) { return(string.Empty); } var foundFiles = new FileSystemEnumerable(new DirectoryInfo(rootDir), fileName, SearchOption.AllDirectories); return(!foundFiles.Any() ? string.Empty : foundFiles.First().FullName); }
/// <summary>Returns an enumerator that iterates through the collection.</summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> public IEnumerator <FileSystemInfo> GetEnumerator() { if (_root == null || !_root.Exists) { yield break; } IEnumerable <FileSystemInfo> matches = new List <FileSystemInfo>(); try { _logger.DebugFormat($"Attempting to enumerate '{_root.FullName}'"); foreach (var pattern in _patterns) { _logger.DebugFormat($"Using pattern '{pattern}'"); matches = matches.Concat(_root.EnumerateDirectories(pattern, SearchOption.TopDirectoryOnly)) .Concat(_root.EnumerateFiles(pattern, SearchOption.TopDirectoryOnly)); } } catch (UnauthorizedAccessException) { _logger.WarnFormat($"Unable to access '{_root.FullName}'. Skipping..."); yield break; } catch (PathTooLongException ptle) { _logger.Warn($@"Could not process path '{_root.Parent?.FullName}\{_root.Name}'.", ptle); yield break; } catch (IOException e) { // "The symbolic link cannot be followed because its type is disabled." // "The specified network name is no longer available." _logger.Warn( $@"Could not process path (check SymlinkEvaluation rules)'{_root.Parent?.FullName}\{_root.Name}'.", e); yield break; } catch { // All other exceptions -- just skip it _logger.Warn( @"Caught an unknown exception. Perhaps we have stumbled upon a file or directory which is protected by the operating system."); yield break; } _logger.DebugFormat($"Returning all objects that match the pattern(s) '{string.Join(",", _patterns)}'"); foreach (var file in matches) { if (file != null) { yield return(file); } } if (_option != SearchOption.AllDirectories) { yield break; } _logger.DebugFormat("Enumerating all child directories."); foreach (var dir in _root.EnumerateDirectories("*", SearchOption.TopDirectoryOnly)) { _logger.DebugFormat($"Enumerating '{dir.FullName}'"); var fileSystemInfos = new FileSystemEnumerable(dir, _patterns, _option); foreach (var match in fileSystemInfos) { if (match != null) { yield return(match); } } } }