Last active
May 14, 2024 05:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!
You have some mentions - https://github.com/HannibalZA/FilePurge/blob/master/FilePurge/Program.cs#L158