jeff
jeff

Reputation: 13643

How to EnumerateFiles with all subdirectories with C# DirectoryInfo?

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 !

Upvotes: 5

Views: 5675

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499860

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();

Upvotes: 14

Related Questions