使用GetFiles函数来获取多种类型的文件扩展名

问题描述 投票:0回答:2

在VB中有一个函数,它要求我获取所有带.pdf和.rtf文件扩展名的文件。当试图包含第二个参数时,我意识到它不会接受第二个参数。

还有一种简单的方法吗?

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

错误:

System.InvalidCastException: 'Conversion from string "*.rtf" to type 'Integer' is not valid.'
vb.net code-behind
2个回答
1
投票

不要在搜索模式下使用GetFiles重载。只需使用一些简单的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)))

0
投票

我在目录中只有两种文件类型(我需要以上所有这些),所以一个简单的解决方案是删除GetFiles函数中仅指示.pdf的参数。

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

不是最好的长期解决方案,但它适用于我现在需要的。

© www.soinside.com 2019 - 2024. All rights reserved.