获取搜索目录的当前目录

Get the current directory of searching directories

我想在 For Each 循环中获取当前目录。我试过使用标签,但它们只是挂起。

这是我当前的代码:

For Each i As String In Directory.GetDirectories("C:\", "*.*", SearchOption.AllDirectories)
   CurDirLbl.Text = i
Next

PS: 这不是恶意的,这是我正在做的一个项目。

Directory.GetDirectories 枚举所有文件和 returns 一个可查询列表。

为了尝试演示,如果您调用代码并进行调试,您将在找到文件和获取目录时暂停 returns,然后将打印出所有文件:

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