get folder to treeview
I am using the following code to get the contents of a folder into a TreeView
. But the current code always adds the contents to the root of the TreeView. It does not add them as child nodes of their parent folder's node.
Can you help me?
void Recurse(string path)
{
DirectoryInfo info = new DirectoryInfo(path);
TreeNode root = new TreeNode(info.Name);
string[] sub = Directory.GetDirectories(info.FullName);
TreeNode node = new TreeNode();
MailTree.Nodes.Add(root);
if (sub.Length == 0) {
}
else
{
开发者_C百科 foreach(string i in sub)
{
DirectoryInfo subinfo = new DirectoryInfo(i);
root.Nodes.Add(subinfo.Name);
Recurse(i);
}
//MailTree.Nodes.Add(root);
}
}
You should be passing a root node as part of your Rescure method, something like Rescure(string path, TreeNode currentRoot)
.
Now, you can call currentRoot.Nodes.Add(root)
in place of MailTree.Nodes.Add(root)
, which will ensure that the brances are added only to the current level. You also need to change your call in the loop to Rescure(i, root)
.
Finally, your initial call to Rescure should include a reference to a pre-created root node, so something like Rescure(initialDirectory, initialRootNode)
.
One thing I would add is that your method and variable names should be changed to reflect their meaning. Yes, you are recursing, but why? A better name for the method might be TraverseDirectory
. Similarly, rather than foreach(string i in sub)
, why not foreach(string directoryName in sub)
? Having clear code is almost as important as having correct code.
The recursive part of your function is always adding the child nodes to the root. You need to add in the "parent node" as a parameter of your recursive function. Something like this:
void Recurse(string path, TreeNode parentNode)
{
DirectoryInfo info = new DirectoryInfo(path);
TreeNode node = new TreeNode(info.Name);
if (parentNode == null)
MailTree.Nodes.Add(node);
else
parentNode.Nodes.Add(node);
string[] sub = Directory.GetDirectories(path);
if (sub.Length != 0)
{
foreach(string i in sub)
{
Recurse(i, node);
}
}
}
I can't se any error in the code at a first glance, but I can suggesto to take another approach: the one you show is too expensive. Just fill a level on the tree, and put some dummy item as a leaf in each nodes you add. Then intercept the NodeExpanding event, remove the dummy node, and add the subnodes ( applying recursively the same strategy of adding the dummy child nodes )
精彩评论