在所有子目录中查找具有特定扩展名的文件数 [英] Find number of files with a specific extension, in all subdirectories
问题描述
int ComponentCount = MagicFindFileCount(@c:\windows\system32, * .DLL);
我知道我可以做一个递归函数来调用Directory.GetFiles,但是会更清晰如果我可以做到这一点,没有所有的迭代。
编辑:如果不可能这样做,而不需要递归和迭代自己,是最好的方法吗?
你应该使用 Directory.GetFiles(path,searchPattern,SearchOption) Directory.GetFiles()的重载。
Path指定路径,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();
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 something like this:
int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.
EDIT: If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?
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();
这篇关于在所有子目录中查找具有特定扩展名的文件数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!