我在vb.net中有一个代码,允许显示目录的树结构。此代码使用递归子过程(sub)来更新TreeView节点,而不使用任何这些方法。我想知道它是如何可能的。这是代码:
Imports System.IO
Public Class Form1
Const DirectoryToList As String = "." ' The current in this case
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Defines the first node
Me.MyTreeView.TopNode = Me.MyTreeView.Nodes.Add(DirectoryToList, DirectoryToList)
'Tree structure of the first node
For Each Directory As String In Directory.GetDirectories(DirectoryToList)
Me.MyTreeView.TopNode.Nodes.Add(Directory, Path.GetFileName(Directory))
'Recursive
ListFolderTree(Directory, Me.MyTreeView.TopNode)
Next
'Files of the first node
For Each File As String In Directory.GetFiles(DirectoryToList)
Me.MyTreeView.TopNode.Nodes.Add(Path.GetFileName(File))
Next
End Sub
' ListFolderTree is the "strange" sub whose operation I don't understand
Sub ListFolderTree(ByVal DirectoryActuel As String, ByVal NodeActuel As TreeNode)
'Recovers the node in which we are
Dim Node As TreeNode = NodeActuel.Nodes(DirectoryActuel)
'Directories of this node
For Each Directory As String In Directory.GetDirectories(DirectoryActuel)
Node.Nodes.Add(Directory, Path.GetFileName(Directory))
'Recursive
ListFolderTree(Directory, Node)
Next
'Files for this node
For Each File As String In Directory.GetFiles(DirectoryActuel)
Node.Nodes.Add(Path.GetFileName(File))
Next
End Sub
End Class
结果是预期的结果,所以树结构。 你能解释一下我对#F; ListFolderTree"" ListFolderTree"子过程? 我知道递归可以将文件和其他文件夹本身放在树中较高的文件夹中,但是如何将数据保存在TreeView控件中?
答案 0 :(得分:0)
在实际目录没有子目录的地方,部分
For Each Directory As String In Directory.GetDirectories(DirectoryActuel)
Node.Nodes.Add(Directory, Path.GetFileName(Directory))
'Recursive
ListFolderTree(Directory, Node)
Next
将是一个没有迭代的循环,因为来自Directory.GetDirectories(DirectoryActuel)
的集合将为空,因此不会进行其他递归调用。