我想在For Each循环中获取当前目录。我已经尝试过使用Labels,但它们只是挂起来了。
这是我目前的代码:
For Each i As String In Directory.GetDirectories("C:\", "*.*", SearchOption.AllDirectories)
CurDirLbl.Text = i
Next
PS:这不是恶意的,它是我正在开展的一个项目。
答案 0 :(得分:1)
Directory.GetDirectories
枚举所有文件并返回可查询列表。
要尝试演示,如果您调用代码并编写调试,则会在找到文件并getDirectories返回时暂停,然后将打印出所有文件:
For Each filename As String In Directory.GetDirectories("C:\", "*.*", SearchOption.AllDirectories)
debug.writeline(filename)
Next
您当然可以自己编写代码来递归枚举目录并报告当前搜索的目录。这不会有效,但在操作过程中会给用户一些反馈:
Private WithEvents _de As New DirectoryEnumerator()
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Dim startPath As String = "C:\Windows\Temp"
_de.StartEnum(startPath)
'now we have the list of files
Debug.WriteLine("Files")
For Each filename In _de.FilesFound
Debug.WriteLine(filename)
Next
End Sub
Private Sub _de_CurrentDirectoryChanged(newDirectory As String) Handles _de.CurrentDirectoryChanged
Debug.WriteLine("Current Directory being searched:" & newDirectory)
End Sub
Private Class DirectoryEnumerator
Private _filesFound As List(Of String)
Public Event CurrentDirectoryChanged(newDirectory As String)
Public ReadOnly Property FilesFound As IReadOnlyList(Of String)
Get
Return _filesFound
End Get
End Property
Public Sub StartEnum(startPath As String)
_filesFound = New List(Of String)
EnumerateDirectory(startPath)
End Sub
Private Sub EnumerateDirectory(thisPath As String)
RaiseEvent CurrentDirectoryChanged(thisPath)
'add any files found in this directory to the list of files
_filesFound.AddRange(Directory.GetFiles(thisPath, "*.*"))
'enumerate any directories found
For Each thisDir In Directory.GetDirectories(thisPath)
EnumerateDirectory(thisDir)
Next
End Sub
End Class