I solved this test project's problem by simplifying what I needed. Here's the final code:
Code:
Imports System.IO
Public Class Form1
Protected Overrides ReadOnly Property CreateParams As CreateParams
Get
CreateParams = MyBase.CreateParams
CreateParams.ExStyle = CreateParams.ExStyle Or &H2000000
Return CreateParams
End Get
End Property
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadRootDrives()
End Sub
Public Sub LoadRootDrives()
For Each Drive As DriveInfo In DriveInfo.GetDrives
Dim node As New TreeNode(Drive.Name)
TreeView1.Nodes.Add(node)
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Removes all child nodes from the Treeview
Try
For Each rootNode2 As TreeNode In TreeView1.Nodes
rootNode2.Nodes.Clear()
Next
Catch ex As Exception
End Try
Dim newPath As String = TextBox1.Text
'Find the node corresponding to the root of the path
Dim rootNode As TreeNode = FindNode(TreeView1.Nodes, Path.GetPathRoot(newPath))
'If the root node is not found, create the root node
If rootNode Is Nothing Then
rootNode = New TreeNode(Path.GetPathRoot(newPath))
TreeView1.Nodes.Add(rootNode)
End If
'Traverse down the treeview to find the nodes corresponding to each subfolder in the path
Dim currentNode As TreeNode = rootNode
Dim subfolders() As String = newPath.Substring(Path.GetPathRoot(newPath).Length).Split(CChar("\"))
For Each subfolder As String In subfolders
If subfolder = "" Then
Continue For
End If
Dim childNode As TreeNode = FindNode(currentNode.Nodes, subfolder)
If childNode Is Nothing Then
'If the node is not found, add it
childNode = New TreeNode(subfolder)
currentNode.Nodes.Add(childNode)
currentNode.Expand() 'expand the current node
End If
currentNode = childNode
Next
'Expand all the nodes to show the subfolder structure
currentNode.Expand()
End Sub
Private Function FindNode(ByVal nodes As TreeNodeCollection, ByVal name As String) As TreeNode
For Each childNode As TreeNode In nodes
If childNode.Text = name Then
Return childNode
End If
Dim foundNode As TreeNode = FindNode(childNode.Nodes, name)
If foundNode IsNot Nothing Then
Return foundNode
End If
Next
Return Nothing
End Function
End Class