0 Replies - 2463 Views - Last Post: 18 February 2016 - 05:16 AM

#1 TechnoBear   User is online

  • Lady A
  • member icon

Reputation: 478
  • View blog
  • Posts: 1,444
  • Joined: 02-November 11

Show All Folders & Subfolders as Hierarchy in TreeView

Posted 18 February 2016 - 05:16 AM

Show All Folders & Subfolders as Hierarchy in TreeView

I figured this would exist already but apparently not, This snippet is a recursive function which just lists all Folders and Subfolders in a TreeView control in Hierarchical order.
- SubFolder

Given it utilizes the TreeView it will need to be a WinForms project, I do believe this control exists in each iteration of .Net

Snippet Code:
''' <summary>
    ''' Add all folders and sub folders to the given TreeNode
    ''' </summary>
    ''' <param name="dir">Directory to search for Subfolders</param>
    ''' <param name="parentNode">Node to attch Subfolders to</param>
    ''' <remarks>This is a recursive function</remarks>
    Private Sub PopulateTreeView(ByVal dir As String, ByVal parentNode As TreeNode)
        Dim folder As String = String.Empty
            'Get list of Subfolders
            Dim folders() As String = IO.Directory.GetDirectories(dir)
            'Ensure Subfolders present
            If folders.Length <> 0 Then
                Dim childNode As TreeNode = Nothing
                'Loop through each Subfolder
                For Each folder In folders
                    'Create node for current Subfolder
                    childNode = New TreeNode(folder)
                    'Add new TreeNode to given Parent Node
                    'Check current Subfolder for Subfolders
                    PopulateTreeView(folder, childNode)
            End If
        Catch ex As UnauthorizedAccessException
            parentNode.Nodes.Add(folder & ": Access Denied")
        End Try
end sub

Usage / Example Code:
To Use the Snippet simply call PopulateTreeView(Directory, RootNode) Like so:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Get a list of drives
        Dim drives As System.Collections.ObjectModel.ReadOnlyCollection(Of IO.DriveInfo) = My.Computer.FileSystem.Drives
        Dim rootDir As String = String.Empty
        'Now loop thru each drive and populate the treeview
        For i As Integer = 0 To drives.Count - 1
            rootDir = drives(i).Name
            'Add this drive as a root node
            'Populate this root node
            PopulateTreeView(rootDir, TreeView1.Nodes(i))
    End Sub

Is This A Good Question/Topic? 2
  • +

Page 1 of 1