How to EnumerateFiles with all subdirectories with C# DirectoryInfo?

半世苍凉 提交于 2019-12-10 19:47:49

问题


I found this code that gets an array of files out of a DirectoryInfo :

FileInfo[] fileInfoArray = di.EnumerateFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray();

But it only searches the direct children of the path of DirectoryInfo. i.e., it does not include grandchildren.

I guess I need to add SearchOption.AllDirectories parameter to somewhere, but where?

I tried :

di.EnumerateFiles(SearchOption.AllDirectories).Where(f => extensions.Contains(f.Extension.ToLower())).ToArray();

But it yields an error.

So how do I search with a pattern, including all subdirectories ?

Thanks for any help !


回答1:


Look at the overloads of DirectoryInfo.EnumerateFiles - there's no overload taking just a SearchOption, but you can give a string and a SearchOption:

var files = di.EnumerateFiles("*", SearchOption.AllDirectories)
              .Where(f => extensions.Contains(f.Extension.ToLower()))
              .ToArray();


来源:https://stackoverflow.com/questions/20253936/how-to-enumeratefiles-with-all-subdirectories-with-c-sharp-directoryinfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!