[RESOLVED] Use TreeView at a specific Directory
I'm just now crossing over from VB6 to VB.net.
I've found all kinds of code to populate TreeView with the drives and subfolders.
I would like to start populating the TreeView at the User's Documents folder.
I'm getting familiar with how the Nodes work, but I'm lost with the System.IO portions.
I'm grateful for any/all help,
Joe
Re: Use TreeView at a specific Directory
Take a look at this example:
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PopulateTreeView(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
End Sub
Private Sub PopulateTreeView(path As String)
' Clear the TreeView control
TreeView1.Nodes.Clear()
' Create the root node for the TreeView
Dim rootNode = New TreeNode(path) With {.Tag = path}
TreeView1.Nodes.Add(rootNode)
' Recursively add child nodes for directories and their files
AddDirectories(rootNode)
End Sub
Private Sub AddDirectories(parentNode As TreeNode)
' Get the path of the parent node
Dim path = DirectCast(parentNode.Tag, String)
' Get the directories in the current path
Dim directories = IO.Directory.GetDirectories(path)
' Add child nodes for each directory
For Each dir As String In directories
Dim directoryNode = New TreeNode(IO.Path.GetFileName(dir)) With {.Tag = dir}
parentNode.Nodes.Add(directoryNode)
Try
' Get the files in the current directory
Dim files = IO.Directory.GetFiles(dir)
' Add child nodes for each file
For Each file In files
Dim fileNode = New TreeNode(IO.Path.GetFileName(file)) With {.Tag = file}
directoryNode.Nodes.Add(fileNode)
Next
' Recursively add child nodes for subdirectories
AddDirectories(directoryNode)
Catch invalidAccessEx As UnauthorizedAccessException
directoryNode.ForeColor = Color.Red
End Try
Next
End Sub
Basically, the AddDirectories method recursively builds TreeNodes. This assumes that you want the path to be stored in the TreeNode's Tag property, which is why PopulateTreeView starts off by creating the root TreeNode and setting it's Tag to the absolute path for MyDocuments.
The important thing to consider is that a lot can go wrong with IO operations. For example, if the user doesn't have sufficient permission to access a file, then an Exception will be thrown.
Edit - I updated the code so that the ForeColor of TreeNodes representing directories will be red if you cannot get the files in the directory.
Re: Use TreeView at a specific Directory
Thank you. This saves me a lot of frustration and a good place to start learning.
Re: Use TreeView at a specific Directory
Quote:
Originally Posted by
Skittles
from VB6 to VB.net
Even 2022! What an athletic jump... I'm older than this to handle that G-Force.
Anyways, I found this on CodeBank and it is quite done beautifully.
Finally, remember to mark the thread as 'Resolved' after you reach an acceptable answer you were looking for.
Re: [RESOLVED] Use TreeView at a specific Directory