Imports System.IO

Public Class Form1

    Private Sub Fill(ByVal Dir As DirectoryInfo, ByVal DirNode As TreeNode)

        ' An exception could be thrown in this code if you don't
        ' have sufficient security exceptions for a file or directory.
        ' You can catch and then ignore this exception.
        Try
            For Each DirItem As DirectoryInfo In Dir.GetDirectories
                ' Add node for the directory.
                Dim NewNode As New TreeNode(DirItem.Name)
                DirNode.Nodes.Add(NewNode)

                ' Use a * as a placeholder for directories that haven't been filled in yet.
                NewNode.Nodes.Add("*")
            Next
        Catch
        End Try
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Fill just the first level.
        Dim RootDir As New DirectoryInfo("c:\")
        Dim RootNode As New TreeNode("c:\")
        treeFiles.Nodes.Add(RootNode)
        Fill(RootDir, RootNode)
    End Sub

    Private Sub treeFiles_BeforeExpand(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles treeFiles.BeforeExpand
        If e.Node.Nodes.Count > 0 Then
            If e.Node.FirstNode.Text = "*" Then
                ' Replace the placeholder with a just-in-time list of directories.
                e.Node.FirstNode.Remove()
                Dim DirectoryToFill As New DirectoryInfo(e.Node.FullPath)
                Fill(DirectoryToFill, e.Node)
            End If
        End If
    End Sub
End Class
