Show Directory Structure in TreeView Just In Time (Windows Form)


I am writing this article to show you how to display directory structure in TreeView Just in Time as Windows Explorer does. We will build sample application as below screen shot that will perform that thing :)



CSharp .net 2.0/3.5


One way to fill the directory structure is to scan through each directory and add nodes in tree view control but this might be time consuming as it takes a lot time to scan whole directory structure.

But here we will fill the tree with some other approach in which we will not scan whole file system at once but we will add node to tree as user clicks [+] Expand of the node that will speed up the process as it does not need to scan thorough whole file system.

So lets get started with our example :)

First drag drop one TreeView control on the form as shown in screenshot.

Here is the whole code . Just read the code I am explaining it in just at the ending about how its working. :)

We are working with the file system so we need to import namespace first 

using System.IO;
private void Form1_Load(object sender, EventArgs e)
    TreeNode rootnode = new TreeNode(@"C:\");
void FillChildNodes(TreeNode node)
       DirectoryInfo dirs = new DirectoryInfo(node.FullPath);
       foreach (DirectoryInfo dir in dirs.GetDirectories())
           TreeNode newnode = new TreeNode(dir.Name);
   catch(Exception ex)
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
   if (e.Node.Nodes[0].Text == "*")

In above code, in load event of the form we have taken one node as we want to add this node in TreeView as rootNode.

Now in second line we are calling function FillChildNodes() method that takes any TreeNode as argument and adds all child directories to the provided node. Here note that we are also adding one node that is  "*" this is because once we expand the node we will clear that node and fill child node of the node that we just expanded. This logic will fill child nodes only if it finds node "*" if its not there then no need to add child nodes under parent.

We written logic of adding child node in treeView1_BeforeExpand() event of the treeView1 so that as soon as user clicks Expand [+] it will check for that "*" node if it found then it will clear that "*" node and fill the child nodes.

In FillChildNode method we are also handling exception as we may some time encounter the exception if we don't have rights to access the directory so that we have handled the exception with try catch block :) 


In this article we have seen how to show directory structure in TreeView control.