0

I have problem searching folder and find all files with specific name. With this method I am able to browse my folder and find all files. But only Word files.

Dim fi As FileInfo() = path.GetFiles(fileName & "*.doc*", SearchOption.AllDirectories)

Now I would like to search Word and PDF. Is there a way how I can find it? If I just write a dot instead of .doc it searches the folder but finds all files. Excel, txt etc.

Dim fi As FileInfo() = path.GetFiles(fileName & "*.*", SearchOption.AllDirectories)

The goal would be to find only certain types of files.

Alex
  • 23
  • 4
  • 3
    Does this answer your question? [How to filter Directory.EnumerateFiles with multiple criteria?](https://stackoverflow.com/questions/3754118/how-to-filter-directory-enumeratefiles-with-multiple-criteria) or [Multiple file-extensions searchPattern for System.IO.Directory.GetFiles](https://stackoverflow.com/questions/7039580/multiple-file-extensions-searchpattern-for-system-io-directory-getfiles) – Michael Phillips Jan 06 '21 at 08:48

1 Answers1

1

It is not possible to use the GetFiles method to enumerate files with multiple extensions. To do that, you'll have to write your own code to do the filtering. I also recommend you use the EnumerateFiles method as it provides better performance over the GetFiles method in most cases.

Here is sample code to do the filtering as you require

Dim filterExtensions = {".docx", ".pdf"}

Dim files = From f In System.IO.Directory.EnumerateFiles("C:\Path", "*.*", _
                                                         SearchOption.AllDirectories)
            Let fi = New FileInfo(f)
            Where filterExtensions.Contains(fi.Extension.ToLower())
            Select fi
Alex Essilfie
  • 12,339
  • 9
  • 70
  • 108
  • I'm not sure why you would use `Directory.EnumerateFiles` and create `FileInfo` objects yourself when you could create a `DirectoryInfo` first and call `EnumerateFiles` on that to get ready-made `FileInfo` objects. – jmcilhinney Jan 06 '21 at 12:31
  • Also, I would tend to use `Where filterExtensions.Any(Function(ext) String.Equals(ext, fi.Extension, StringComparison.InvariantCultureIgnoreCase))`. – jmcilhinney Jan 06 '21 at 12:33
  • *"the EnumerateFiles method as it provides better performance over the GetFiles method in most cases"*. If you intend to enumerate the results then yes. If you were going to bind the results or something like that then you need an `IList` anyway, so the array returned by `GetFiles` fits the bill. Otherwise, you'd have to call `ToArray` or the like anyway. – jmcilhinney Jan 06 '21 at 12:41