Visual Basic: Recursive directory treeview

Platform:Visual Basic
Task:Recursive directory treeview
Discussion:
Recursive directory treeview
Example:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim RootDir As String = "C:\Temp"
        Dim RootNode As New TreeNode(RootDir)
        Me.TreeView1.Nodes.Add(RootNode)
        AddSubDIrectoryNodes(RootNode, RootDir, False)
    End Sub

    Private Sub AddSubDIrectoryNodes(ByVal ParentNode As TreeNode, ByVal Directory As String, ByVal PreloadSubdirectories As Boolean)
        'directories
        If My.Computer.FileSystem.DirectoryExists(Directory) Then
            For Each Dir As String In My.Computer.FileSystem.GetDirectories(Directory)
                Dim Node As New TreeNode
                Node.Name = My.Computer.FileSystem.GetFileInfo(Dir).Name
                Node.Text = My.Computer.FileSystem.GetFileInfo(Dir).Name
                Node.Tag = Dir
                Node.ImageIndex = 0
                Node.SelectedImageIndex = 1
                'also recursively loads subdirectories, very slow
                If PreloadSubdirectories = True Then
                    AddSubDIrectoryNodes(Node, Node.Tag, PreloadSubdirectories)
                End If
                ParentNode.Nodes.Add(Node)
            Next
        End If

        'files
        For Each DirFile As String In My.Computer.FileSystem.GetFiles(Directory)
            Dim Node As New TreeNode
            Node.Name = My.Computer.FileSystem.GetFileInfo(DirFile).Name
            Node.Text = My.Computer.FileSystem.GetFileInfo(DirFile).Name
            Node.Tag = DirFile
            Node.ImageIndex = 2
            Node.SelectedImageIndex = 3
            ParentNode.Nodes.Add(Node)
        Next
    End Sub


    Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        AddSubDIrectoryNodes(e.Node, Me.TreeView1.SelectedNode.Tag, False)
        e.Node.Expand()
    End Sub
End Class
Back to Index