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

List all folders that are in any 3rd subdirectory from current

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

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

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

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