Jacked_Nerd
Jacked_Nerd

Reputation: 237

Using GetFiles function to grab multiple types of file extensions

Have a function in VB that requires me to get all files with .pdf and .rtf file extensions. When trying to include a second parameter, I realized it will not accept the second argument.

Is there an easy way to do this still?

Dim s() As String = System.IO.Directory.GetFiles(Server.MapPath("PrintableForms.aspx").Replace("PrintableForms.aspx", "Forums\"), "*.pdf")

error:

System.InvalidCastException: 'Conversion from string "*.rtf" to type 'Integer' is not valid.'

Upvotes: 0

Views: 272

Answers (2)

djv
djv

Reputation: 15774

Don't bother with the GetFiles overload with the search pattern. Just do the filtering with some simple LINQ

' an array of the extensions
Dim extensions = {".pdf", ".rtf"}
' the path to search
Dim path = Server.MapPath("PrintableForms.aspx").Replace("PrintableForms.aspx", "Forums\")
' get only files in the path
Dim allFileNames = Directory.GetFiles(path)
' get files in the path and its subdirectories
'Dim allFileNames = Directory.GetFiles(path:=path, searchOption:=SearchOption.AllDirectories)
' get the filenames which have any of the extensions in the array above
Dim filteredFileNames = allFileNames.Where(Function(fn) extensions.Contains(System.IO.Path.GetExtension(fn)))

Upvotes: 1

Jacked_Nerd
Jacked_Nerd

Reputation: 237

I only have two files types in the directory (of which I need all of the above) so a simple solution would be to remove the parameter in the GetFiles function that dictates for just .pdf.

Dim s() As String = System.IO.Directory.GetFiles(Server.MapPath("PrintableForms.aspx").Replace("PrintableForms.aspx", "Forums\"))

Not the best long-term solution, but it works for what I need now.

Upvotes: 0

Related Questions