Skip to content

Instantly share code, notes, and snippets.

@smith-neil
Last active May 14, 2024 05:25
Show Gist options
  • Select an option

  • Save smith-neil/9403767 to your computer and use it in GitHub Desktop.

Select an option

Save smith-neil/9403767 to your computer and use it in GitHub Desktop.
c# recursive function used to search for a file by name in a given directory and all subdirectories under the given root
IEnumerable<string> SearchAccessibleFiles(string root, string searchTerm) {
var files = new List<string>();
foreach (var file in Directory.EnumerateFiles(root).Where(m => m.Contains(searchTerm))) {
files.Add(file);
}
foreach (var subDir in Directory.EnumerateDirectories(root)) {
try {
files.AddRange(SearchAccessibleFiles(subDir, searchTerm));
}
catch (UnauthorizedAccessException ex) {
// ...
}
}
return files;
}
// use example:
// var files = SearchAccesibleFiles(@"c:\", "bugs");
// will return every file on the c drive, in an accessible directory, with a name that contains 'bugs'
@HannibalZA

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment