Recursive Search for a Single File

I recently had to write a routine to search for the location of a particular file in a directory tree. I could find lots of code to create an array of all the filenames in the tree, but I needed to just retrieve the location of the filename I was looking for. So, here's the code:


        public static string SearchForSingleFile(string path, string fileName)
        {
            string searchPath = Path.Combine(path, fileName);

            if (File.Exists(searchPath))
            {
                return searchPath;
            }

            string foundFile = string.Empty;
            string[] dirs = Directory.GetDirectories(path);

            foreach (string dir in dirs)
            {
                foundFile = SearchForSingleFile(dir, fileName);

                if (foundFile != String.Empty)
                    break;
            }

            return foundFile;
        }
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
Print | posted on Saturday, August 16, 2008 2:18 AM
Comments have been closed on this topic.