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

#1 TechnoBear  Icon User is offline

  • Lady A
  • member icon

Reputation: 185
  • View blog
  • Posts: 818
  • 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.
e.x:
Folder
- SubFolder
-SubFolder

Requirements:
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
        Try
            '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
                    parentNode.Nodes.Add(childNode)
                    'Check current Subfolder for Subfolders
                    PopulateTreeView(folder, childNode)
                Next
            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
            TreeView1.Nodes.Add(rootDir)
            'Populate this root node
            PopulateTreeView(rootDir, TreeView1.Nodes(i))
        Next
    End Sub


Is This A Good Question/Topic? 2
  • +

Page 1 of 1