2

I wish to get list of all the folders/directories that has a particular file in it. How do I do this using C# code.

Eg: Consider I have 20 folders of which 7 of them have a file named "abc.txt". I wish to know all folders that has the file "abc.txt".

I know that we can do this by looking thru all the folders in the path and for each check if the File.Exists(filename); But I wish to know if there is any other way of doing the same rather than looping through all the folder (which may me little time consuming in the case when there are many folders).

Thanks
-Nayan

1
  • You have to do it Recursively as far as I'm aware I'm afraid.
    – Derek
    Feb 6, 2013 at 8:43

2 Answers 2

9

I would use the method EnumerateFiles of the Directory class with a search pattern and the SearchOption to include AllDirectories. This will return all files (full filename including directory) that match the pattern.

Using the Path class you get the directory of the file.

string rootDirectory = //your root directory;
var foundFiles = Directory.EnumerateFiles(rootDirectory , "abc.txt", SearchOption.AllDirectories);

foreach (var file in foundFiles){
  Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}

EnumerateFiles is only available since .NET Framework 4. If you are working with an older version of the .NET Framework then you could use GetFiles of the Directory class.

Update (see comment from PLB):

The code above will fail if the access to a directory in denied. In this case you will need to search each directory one after one to handle exceptions.

public static void SearchFilesRecursivAndPrintOut(string root, string pattern)
{
    //Console.WriteLine(root);
    try
    {
        var childDireactory = Directory.EnumerateDirectories(root);
        var files = Directory.EnumerateFiles(root, pattern);

        foreach (var file in files)
        {
            Console.WriteLine(System.IO.Path.GetDirectoryName(file));
        }

        foreach (var dir in childDireactory)
        {
            SearchRecursiv(dir, pattern);
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
    }
}
10
  • 4
    One drawback of this aproach is that it will throw UnauthorizedAccessException if at least one sub-folder is inaccessible.
    – Leri
    Feb 6, 2013 at 8:54
  • @Jehof - This approach did not work.. I tried the same.. EnumerateFiles returns me empty list :( I am using .NET 4
    – Nayan Soni
    Feb 6, 2013 at 9:01
  • @NayanSoni: then no file is found. or your search pattern is incorrect or you are searching the wrong directory.
    – Jehof
    Feb 6, 2013 at 9:05
  • @Jehof You're welcome. Generally I use recursive scan and mute these exceptions. It took 00:00:20.8214437 to scan my C drive (~400K files) with search pattern *.
    – Leri
    Feb 6, 2013 at 9:07
  • 1
    @NayanSoni: Nice that it works now. I have added a recursive method to search for files, to handle the case of an exception. see also PLBs comment
    – Jehof
    Feb 6, 2013 at 9:24
0

The following shows how to narrow down your search by specific criteria (i.e. include only DLLs that contain "Microsoft", "IBM" or "nHibernate" in its name).

var filez = Directory.EnumerateFiles(@"c:\MLBWRT", "*.dll", SearchOption.AllDirectories)
        .Where(
            s => s.ToLower().Contains("microsoft")
            && s.ToLower().Contains("ibm")
            && s.ToLower().Contains("nhibernate"));
string[] allFiles = filez.ToArray<string>();
for (int i = 0; i < allFiles.Length; i++) {
    FileInfo fInfo = new FileInfo(allFiles[i]);
    Console.WriteLine(fInfo.Name);
}
1
  • you should use EnumerateFiles as you're adding a where clause it your search, also this will look for file that contain "microsoft" and "ibm" and "nhibernate" you might want to change that.
    – Eluvatar
    Oct 9, 2013 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.