出于某种原因,似乎外部块似乎没有像我预期的那样递归更新。我希望循环将"C:\Users\Drise"
中的所有目录添加到数组internaldirs()
。关于正确的方法的任何建议,因为我似乎做得不正确?
Static internaldirs() As String
internaldirs.add("C:\Users\Drise")
For Each internaldir As String In internaldirs
For Each direc As String In Directory.GetDirectories(internaldir)
internaldirs.Add(direc)
Next
Next
解决方案:
Sub recursivedirs()
Static internaldirs As New List(Of String)
Try
If internaldirs(0) = "C:\Users\Drise" Then
Call AddDirToList(internaldirs, internaldirs(0))
End If
Catch
internaldirs.Add("C:\Users\Drise")
Call AddDirToList(internaldirs, internaldirs(0))
End Try
End Sub
Private Sub AddDirToList(ByRef dirs As List(Of String), ByVal currentDir As String)
dirs.Add(currentDir)
Try
For Each subDir As String In Directory.GetDirectories(currentDir)
AddDirToList(dirs, subDir)
Next
Catch
End Try
答案 0 :(得分:2)
简短回答是:你不能修改你正在迭代的集合(内部)。
更长的答案:看起来你正在尝试构建一个列出目录树中文件夹的字符串数组。更好的方法是使用List和递归函数。
Static dirs As List(Of String)
dirs = New List(Of String)
AddDirToList(dirs, "C:\Users\Drise")
Private Sub AddDirToList (dirs as List(Of String), currentDir as String)
dirs.Add(currentDir)
For Each subDir As String In Directory.GetDirectories(currentDir)
AddDirToList(dirs, currentDir)
Next
End Sub
请原谅任何语法问题。我更像是一个C#家伙。
答案 1 :(得分:0)
正如Andrew Cooper所说,你无法修改For Each
循环中使用的集合。
您可以使用索引计数器。
Dim internaldir As List(Of String)
internaldir.Add("C:\Users\Drise")
Dim i As Integer = 0
Do Until i >= internaldir.Count
Dim internaldir As String = internaldirs(i)
For Each currentdir As String In Directory.GetDirectories(internaldir)
internaldirs.Add(currentdir)
Next
i += 1
Loop
' If you want an array as output, use:
Dim array As String() = internaldirs.ToArray()