Initialize a TreeView control to display a directory hierarchy in C#

[TreeView control]

This example adds the following LoadFromDirectory extension method to the TreeView control.

// Initialize the TreeView from a directory,
// its subdirectories, and their files.
public static void LoadFromDirectory(this TreeView trv,
    string directory, int folder_img, int file_img)
    DirectoryInfo dir_info = new DirectoryInfo(directory);
    AddDirectoryNodes(trv, dir_info, null, folder_img, file_img);

This method creates a DirectoryInfo object to represent the directory that should be loaded into the TreeView. It then calls the following AddDirectoryNode method.

// Add this directory's node and sub-nodes.
public static void AddDirectoryNodes(TreeView trv,
    DirectoryInfo dir_info, TreeNode parent, int folder_img, int file_img)
    // Add the directory's node.
    TreeNode dir_node;
    if (parent == null) dir_node = trv.Nodes.Add(dir_info.Name);
    else dir_node = parent.Nodes.Add(dir_info.Name);

    // Add the folder image.
    if (folder_img >= 0) dir_node.ImageIndex = folder_img;

    // Add subdirectories.
    foreach (DirectoryInfo subdir in dir_info.GetDirectories())
        AddDirectoryNodes(trv, subdir, dir_node, folder_img, file_img);

    // Add file nodes.
    foreach (FileInfo file_info in dir_info.GetFiles())
        TreeNode file_node = dir_node.Nodes.Add(file_info.Name);
        if (file_img >= 0) file_node.ImageIndex = file_img;

This method creates a TreeView node to represent the directory. If the parent parameter is null, it adds the node to the TreeView control’s Nodes collection. Otherwise it adds the new node below the parent node. (This allows a program to add multiple top-level directories to the TreeView if desired.)

If the folder_img parameter is at least 0, then the method sets the node’s ImageIndex property to that value so the node displays an image. In this example, folders display a little folder image.

Next, the method loops through the directory’s subdirectories, recursively calling AddDirectoryNodes for each. This makes the directory’s subdirectories come before the directory’s files.

Finally, the method loops through the directory’s files, adding nodes below the directory’s node. If the file_img parameter is at least 0, the method sets the new nodes’ ImageIndex properties so they display the file image. In this example, that’s a little picture of a document.

Two enhancements I can think of would be to display appropriate images for different file types and to provide a context menu so, for example, the user can open or delete a file. If I have time, I may work on those. If you build them first, post a comment below.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in controls, directories, extension methods, files, user interface and tagged , , , , , , , , , , , , , . Bookmark the permalink.