Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created July 10, 2023 18:29
Show Gist options
  • Select an option

  • Save ramonsmits/17c85c439b157defa7203a45d3a4a1c7 to your computer and use it in GitHub Desktop.

Select an option

Save ramonsmits/17c85c439b157defa7203a45d3a4a1c7 to your computer and use it in GitHub Desktop.
Search for a file in the directory tree
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