Subscribe

RSS Feed (xml)

Show a JIT Directory Tree in TreeView Control

You can use recursion to build an entire directory tree. However, scanning the file system in this way can be slow, particularly for large drives. For this reason, professional file management software programs (including Windows Explorer) use a different technique-querying the necessary directory information when the user requests it.

The TreeView control is particularly well suited to this approach because it provides a BeforeExpand event that fires before a new level of nodes is displayed. You can use a placeholder (such as an asterisk or empty TreeNode) in all the directory branches that aren't filled in. This allows you to fill in parts of the directory tree as they are displayed.

To use this type of solution, you need the following three ingredients:

  • A Fill method that adds a single level of directory nodes based on a single directory. You'll use this method to fill directory levels as they are expanded.

  • A basic Form.Load event handler that uses the Fill method to add the first level of directories for the drive.

  • A TreeView.BeforeExpand event handler that reacts when the user expands a node and calls the Fill method if this directory information has not yet been added.

Here's the full form code for this solution:

using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;

public class DirectoryTree : System.Windows.Forms.Form {

    private System.Windows.Forms.TreeView treeDirectory;

    // (Designer code omitted.)

    private void Fill(TreeNode dirNode) {

        DirectoryInfo dir = new DirectoryInfo(dirNode.FullPath);
            
        // An exception could be thrown in this code if you don't
        // have sufficient security permissions for a file or directory.
        // You can catch and then ignore this exception.
        foreach (DirectoryInfo dirItem in dir.GetDirectories()) {

            // Add node for the directory.
            TreeNode newNode = new TreeNode(dirItem.Name);
            dirNode.Nodes.Add(newNode);
            newNode.Nodes.Add("*");
        }
    }

    private void DirectoryTree_Load(object sender, System.EventArgs e) {

        // Set the first node.
        TreeNode rootNode = new TreeNode("C:\\");
        treeDirectory.Nodes.Add(rootNode);

        // Fill the first level and expand it.
        Fill(rootNode);
        treeDirectory.Nodes[0].Expand();
    }

    private void treeDirectory_BeforeExpand(object sender, 
      System.Windows.Forms.TreeViewCancelEventArgs e) {

        // If a dummy node is found, remove it and read the 
        // real directory list.
        if (e.Node.Nodes[0].Text == "*") {

            e.Node.Nodes.Clear();
            Fill(e.Node);
        }
    }
}

Technorati :

4 comments:

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail