vb.net - 使用 GetFiles 函数抓取多种类型的文件扩展名
问题描述
在 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.'
解决方案
不要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)))