Showing directory structure in TreeView control using c# :
This blog will walk you through using a tree view control of the windows forms
application in .net to show the directory structure on your computer. Create a
windows form application in visual studio. Drag and drop the tree view control
on the form design.
Code at Form load :
Here we specify the Directory path from where we want to show the directory
structure and call a method to populate the treeView.
private
void Form1_Load(object
sender, EventArgs e)
{
DirectoryInfo root =
new DirectoryInfo(@"D:\folder");
TreeNode node = populateTree(root,null);
treeView1.Nodes.Add(node);
}
Now we write the method populateTree which is called in the form load.
This method is recursively called which allows it to read through the nesting of
the directories.
TreeNode
populateTree(DirectoryInfo root,
TreeNode parent)
{
TreeNode node = new
TreeNode(root.Name);
DirectoryInfo[] subdirs = root.GetDirectories();
foreach (DirectoryInfo
subdir in subdirs) {
populateTree(subdir,node);
}
if (parent == null)
{
return node;
}
else
{
parent.Nodes.Add(node);
return parent;
}
}
In this method we are passing the root (ie the path starting from which we want
to show the directory structure) and its parent which is Initially NULL
For each subdirectory in the root and sub-sub directories and so on, we call the
method recursively by passing the appropriate parent. This method drills down
through the directory structure and creates an appropriate parent-child
hierarchy.
The result will be a tree view showing the structure of the folders