Find number of files with a specific extension, in all subdirectories

前端 未结 7 1758
执念已碎
执念已碎 2020-12-03 07:16

Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for somet

7条回答
  •  有刺的猬
    2020-12-03 08:15

    You should use the Directory.GetFiles(path, searchPattern, SearchOption) overload of Directory.GetFiles().

    Path specifies the path, searchPattern specifies your wildcards (e.g., *, *.format) and SearchOption provides the option to include subdirectories.

    The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:

    string[] files = directory.GetFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories);
    
    return files.Length;
    

    EDIT: Alternatively you can use Directory.EnumerateFiles method

    return Directory.EnumerateFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories).Count();
    

提交回复
热议问题