Vb.net 列出当前文件夹中任何第三个子目录中的所有文件夹

Vb.net 列出当前文件夹中任何第三个子目录中的所有文件夹,vb.net,list,directory,subdirectory,Vb.net,List,Directory,Subdirectory,我需要制作一个数组列表,显示当前子文件夹中第三个子文件夹中的所有文件夹 Folder1/sub1folder/sub2folder/sub3folder 它必须是递归的。我需要的是一个字符串数组,它包含上面提到的所有字符串。 我知道如何递归地查看文件夹,但我不知道如何将搜索限制到第三个子文件夹 谢谢 如果您有一个从当前文件夹开始的递归函数: Public Function recurse(Optional depth As Integer = 0) As String() Dim fold

我需要制作一个数组列表,显示当前子文件夹中第三个子文件夹中的所有文件夹

Folder1/sub1folder/sub2folder/sub3folder
它必须是递归的。我需要的是一个字符串数组,它包含上面提到的所有字符串。 我知道如何递归地查看文件夹,但我不知道如何将搜索限制到第三个子文件夹


谢谢

如果您有一个从当前文件夹开始的递归函数:

Public Function recurse(Optional depth As Integer = 0) As String()
  Dim folderList As String()
  If (depth < 3) Then
    depth += 1
    folderList = recurse(depth)
  Else
    'Do third subfolder analysis and set the output to folderList
    Return folderList
  End If
End Sub
公共函数递归(可选深度为整数=0)为字符串()
Dim folderList作为字符串()
如果(深度<3),则
深度+=1
folderList=递归(深度)
其他的
'执行第三个子文件夹分析并将输出设置为folderList
返回文件夹列表
如果结束
端接头

这是我的尝试。我测试了它,它对我有效:

Dim resultList as List(Of String) = DirectorySearch(baseDirectoryPath, 0)

Function DirectorySearch(directoryPath As String, level As Integer) As List(Of String)

    level += 1

    Dim directories As String() = IO.Directory.GetDirectories(directoryPath)

    Dim resultList As New List(Of String)

    If level = 3 Then
        For Each subDirectoryPath In directories
            Dim result As String = GetFinalResult(subDirectoryPath)
            resultList.Add(result)
        Next
    Else
        For Each subDirectoryPath In directories
            Dim partialResultList As List(Of String) = DirectorySearch(subDirectoryPath, level)
            resultList.AddRange(partialResultList)
        Next
    End If

    Return resultList

End Function

Private Function GetFinalResult(directoryPath As String) As String
    Dim directoryInfo As New IO.DirectoryInfo(directoryPath)
    Return String.Format("{0}/{1}/{2}/{3}",
                         directoryInfo.Parent.Parent.Parent.Name,
                         directoryInfo.Parent.Parent.Name,
                         directoryInfo.Parent.Name,
                         directoryInfo.Name)
End Function

在您的递归过程中,使用当前深度的参数。非常欢迎您,我很高兴它适合您。另外:如果您想概括级别深度(当前固定为3),可以在DirectorySearch中将其作为参数传递,然后将GetFinalResult构建为一个函数,递归地将每个directoryInfo.Parent获取到所需级别。