Created
July 10, 2023 18:29
-
-
Save ramonsmits/17c85c439b157defa7203a45d3a4a1c7 to your computer and use it in GitHub Desktop.
Search for a file in the directory tree
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
| using System; | |
| using System.IO; | |
| using System.Linq; | |
| static class PathWalker | |
| { | |
| public static string Find(string filename, string path) | |
| { | |
| if (filename == null) throw new ArgumentNullException(nameof(filename)); | |
| if (path == null) throw new ArgumentNullException(nameof(path)); | |
| var directory = new DirectoryInfo(path); | |
| while (true) | |
| { | |
| var file = directory.EnumerateFiles(filename).FirstOrDefault(); | |
| if (file is not null) | |
| { | |
| return file.FullName; | |
| } | |
| directory = directory.Parent ?? throw new ArgumentOutOfRangeException(nameof(filename), filename, "Unable to find file in path"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment