0

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.'
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Jacked_Nerd
  • 209
  • 3
  • 12
  • 1
    You can see one way in [Searching for file in directories recursively](https://stackoverflow.com/a/9830116/1115360). I guess that you don't need the `SearchOption.AllDirectories`, and that you meant to put in a *directory* name instead of "PrintableForms.aspx". – Andrew Morton Mar 21 '19 at 16:12
  • @AndrewMorton will this work in VB though? – Jacked_Nerd Mar 21 '19 at 16:14
  • @Jacked_Nerd : Yes. Most basic C# code has a VB.NET equivalent (and vice versa). You can use an online converter such as [Telerik](https://converter.telerik.com/). – Visual Vincent Mar 21 '19 at 16:17
  • Essentially yes, e.g. the first line would be `Dim extensions As New List(Of String) From {".pdf", ".rtf"}`. – Andrew Morton Mar 21 '19 at 16:17
  • @AndrewMorton I have edited the code in my original post. You were right, I was missing directory – Jacked_Nerd Mar 21 '19 at 16:18

2 Answers2

1

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)))
djv
  • 15,168
  • 7
  • 48
  • 72
0

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.

Jacked_Nerd
  • 209
  • 3
  • 12
  • `GetFiles(Server.MapPath("PrintableForms.aspx").Replace("PrintableForms.aspx", "Forums\"))` should be `GetFiles(Server.MapPath("~/Forums"))`, which is a bit easier on the eyes. – Andrew Morton Mar 21 '19 at 16:28