我正在尝试对文件夹执行搜索并获取每个结果的数组。我找到了这段代码,但它没有进入子文件夹:
Dim Results As New List(Of String)
For Each strFileName As String In IO.Directory.GetFiles("pathToSearch")
If strFileName.Contains("searchTerm") Then
Results.Add(strFileName)
End If
Next
我该如何做到这一点,还要查看子文件夹?
我对VB.NET中的搜索选项知之甚少,所以如果这看起来很愚蠢,我会提前道歉。我试过在网上搜索但没找到任何东西。我不能有一个字符串,它需要是一个数组(这需要稍后在程序中由机器解释)
感谢您的帮助
答案 0 :(得分:1)
不需要递归。这已经超载了。您只需要使用适当的搜索选项调用它。
e.g。要列出目录中的所有txt文件以及您可以执行的子目录:
Dim foundFiles() As String = System.IO.Directory.GetFiles("path/to/dir", "*.txt", System.IO.SearchOption.AllDirectories)
答案 1 :(得分:0)
为了获取子文件夹,您可以尝试一些递归函数
答案 2 :(得分:0)
除非有一个我不熟悉的文件系统搜索API,否则这将涉及一个递归方法来执行搜索子目录。
有帮助的是,微软甚至has a complete example of something very similar可用。在VB中它可能看起来像这样(我的VB 非常生锈,这是免费代码,顺便说一下......):
Function FindFiles(ByVal dir As String, ByVal searchTerm As String) As List(Of String)
Dim Results As New List(Of String)
' search files in this directory
For Each strFileName As String In IO.Directory.GetFiles(dir)
If strFileName.Contains(searchTerm) Then
Results.Add(strFileName)
End If
Next
' recurse into child directories
For Each strDirectoryName As String In IO.Directory.GetDirectories(dir)
Results = Results.AddRange(FindFiles(strDirectoryName, searchTerm)
Next
Return Results
End Function
答案 3 :(得分:0)
创建一个递归函数,一直调用自己,直到检查完所有子目录:
Private Function GetAllFileNamesFromDirectory(ByVal strPath As String, ByVal strSearchTerm As String) As List(Of String)
Dim lstFileNames As New List(Of String)
Dim lstSubDirectories As List(Of String) = IO.Directory.GetDirectories(strPath).ToList()
Dim lstFilesToAdd As List(Of String) = IO.Directory.GetFiles(strPath).ToList()
For Each strFileToAdd As String In lstFilesToAdd
If strFileToAdd.Contains(strSearchTerm) Then
'Additional logic would be required to filter out the directory name.
lstFileNames.Add(strFileToAdd)
End If
Next
If lstSubDirectories.Count > 0 Then
lstSubDirectories.ForEach(Sub(strDirectoryPath As String)
Dim lstSubDirectoryFilesToAdd As List(Of String) = GetAllFileNamesFromDirectory(strDirectoryPath, strSearchTerm)
If lstSubDirectoryFilesToAdd.Count > 0 Then
lstFileNames.AddRange(lstSubDirectoryFilesToAdd)
End If
End Sub)
End If
Return lstFileNames
End Function