在所有子目录中查找具有特定扩展名的文件数

时间:2020-03-05 18:43:10  来源:igfitidea点击:

有没有一种方法可以查找特定类型的文件数,而不必遍历Directory.GetFiles()或者类似方法中的所有结果?我正在寻找这样的东西:

int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");

我知道我可以创建一个递归函数来调用Directory.GetFiles,但是如果我无需进行所有迭代就可以做到这一点将更加干净。

编辑:如果不进行递归和迭代就不可能做到这一点,那么什么是最好的方法呢?

解决方案

回答

有人必须做重复的部分。

AFAIK,.NET中已经不存在这样的方法,所以我想有人必须是我们。

回答

我们应该使用Directory.GetFiles()的Directory.GetFiles(path,searchPattern,SearchOption)重载。

路径指定路径,searchPattern指定通配符(例如*,*。format),SearchOption提供包含子目录的选项。

此搜索的返回数组的Length属性将为特定搜索模式和选项提供正确的文件数:

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

return files.Length;

编辑:或者,我们可以使用Directory.EnumerateFiles方法

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

回答

我们可以使用此GetFiles重载:

Directory.GetFiles Method (String,
   String, SearchOption)

以及SearchOption的该成员:

AllDirectories - Includes the current
  directory and all the subdirectories
  in a search operation. This option
  includes reparse points like mounted
  drives and symbolic links in the
  search.

GetFiles返回一个字符串数组,因此我们只需获取Length(即找到的文件数)即可。

回答

使用递归,MagicFindFileCount看起来像这样:

private int MagicFindFileCount( string strDirectory, string strFilter ) {
     int nFiles = Directory.GetFiles( strDirectory, strFilter ).Length;

     foreach( String dir in Directory.GetDirectories( strDirectory ) ) {
        nFiles += GetNumberOfFiles(dir, strFilter);
     }

     return nFiles;
  }

尽管乔恩的解决方案可能是更好的解决方案。