has always been to the understanding of recursion is not deep, sometimes feel very simple, but it will always go wrong. There is a need to display all directories and files under a folder in the TreeView control, with no unintended need for recursion.
At first, it was thought to write a recursive method to generate each node (TreeNode), and finally add the root node to the TreeView.
1 Private StaticTreeNode Getrootnode (stringdirname)//Traverse all subdirectories and files and generate nodes based on the address of the Incoming folder2 {3TreeNode node =NewTreeNode (dirname);4 string[] dirs =directory.getdirectories (dirname);5 string[] files =Directory.GetFiles (dirname);6 7 foreach(stringDirinchdirs)8 {9 node. Nodes.Add (dir); Getrootnode (dir); One } A - - foreach(stringFileinchfiles) the { - -TreeNode Fnode =NewTreeNode (file); - node. Nodes.Add (Fnode); + - } + A returnnode; at}
The result is not as I thought, it simply iterates through all the directories in the root directory and generates a child node of the root node. The results are as follows:
Only the root node and the first-level child node, the files under the subdirectory and the level two subdirectory are gone. The key is in the Red Code section, where I recursive, but did not add the resulting child nodes to the previous level node.
The key or the understanding of recursion is too superficial.
Here are the corrected codes and results:
public static Boolean Createtree (TreeView tree,string dirname) {TreeNode root; if ((Root=getrootnode (dirname)) = = null) return false; Tree. Nodes.Add (root); return true; } private static TreeNode Getrootnode (string dirname)//recursive, return root node {TreeNode node = new TreeNode (di Rname); string[] dirs = directory.getdirectories (dirname); string[] files = directory.getfiles (dirname); foreach (String dir in dirs) {node. Nodes.Add (Getrootnode (dir));} foreach (string file in files) {if (path.getextension (file) = = ". C" | | Path.getextension (file) = = ". h") {TreeNode Fnode = new TreeNode (file); Node. Nodes.Add (Fnode); }} return node; }
Results:
It's a little bit of progress here.
The C#treeview control traverses all subfolders and files under the folder