您可以使用以下代碼來實現通過TreeView控件顯示文件夾下所有文件列表的功能:
Private Sub PopulateTreeView(ByVal path As String, ByVal parentNode As TreeNode)
Dim folder As String = String.Empty
Try
Dim folders() As String = IO.Directory.GetDirectories(path)
If folders.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each folder In folders
childNode = New TreeNode(folder)
parentNode.Nodes.Add(childNode)
PopulateTreeView(folder, childNode)
Next
End If
Dim files() As String = IO.Directory.GetFiles(path)
If files.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each file In files
childNode = New TreeNode(IO.Path.GetFileName(file))
parentNode.Nodes.Add(childNode)
Next
End If
Catch ex As UnauthorizedAccessException
parentNode.Nodes.Add("Access Denied")
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim rootPath As String = "C:\YourFolderPath" '指定文件夾路徑
Dim rootNode As New TreeNode(rootPath)
TreeView1.Nodes.Add(rootNode)
PopulateTreeView(rootPath, rootNode)
End Sub
這段代碼通過遞歸遍歷文件夾,將每個文件夾和文件都添加到TreeView控件中的對應節點。您只需要將rootPath
變量替換為您想顯示文件列表的文件夾路徑即可。