Daniel K. Daniel K. - 5 months ago 18x
Vb.net Question

Get the current directory of searching directories

I want to get the current directory on a For Each loop. I've tried it with Labels, but they just hang.

Here is my current Code:

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

PS: This is not for anything malicious, it's an project I am working on.


Directory.GetDirectories enumerates all the files and returns a queryable list.

To try and demonstrate, if you call your code and write out debug you will get a pause while the files are found and getDirectories returns, then all of the files will be printed out:

For Each filename As String In Directory.GetDirectories("C:\", "*.*", SearchOption.AllDirectories)

You can of course code something yourself that enumerates directories recursively and reports the directory it is current searching. This won't be as efficient but it will give some feedback to the user while the operation is in progress:

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"

    'now we have the list of files 
    For Each filename In _de.FilesFound
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)
            Return _filesFound
        End Get
    End Property
    Public Sub StartEnum(startPath As String)
        _filesFound = New List(Of String)
    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)
    End Sub
End Class