Display Sub Directories And Files In TreeView

In this article, I am going to share with you how to display subdirectories and files in TreeView in C#.

Here, we are going to learn to display the subdirectories and files into TreeView by using Tooltip. On mouse-hover, it will display the path of the file or folder. This article will help you to understand the TreeView and TreeNode’s concepts.

Targeted Audiences

The targeted audience is people with basic knowledge of C#.

Explanation

Things to do,

  • Make a C# WinForm application.
  • Create UI
  • Code

Create a new project and give it a suitable name as I gave the project name, ‘DisplayDirectoryTreeview’.

Now, make a UI which contains two Buttons, one Textbox, one ProgressBar, a single TreeView, FolderBrowserDialog, ImageList and ToolTip tool. So here, our UI looks like the following.

Now, I will explain the functionality of these components which we used in our form. There is Textbox which we used to take User input for directory path, same we have used FolderBrowserDialog for the same purpose, ImageList to store the Folder and File Icons Images, Progressbar to showing the progress. After selecting the Directory path, user can click ‘Load Directory’ button to load the selected directory.

Code

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

Code for the folder browse button click event.

private void btnDirectoryPath_Click(object sender, EventArgs e)  
{  
    folderBrowserDialog1.SelectedPath = txtDirectoryPath.Text;  
    DialogResult drResult = folderBrowserDialog1.ShowDialog();  
    if (drResult == System.Windows.Forms.DialogResult.OK)  
        txtDirectoryPath.Text = folderBrowserDialog1.SelectedPath;
}

Code for the ‘Load Directory’ button click event. In this function, we are clearing the old data such as resetting the progressbar value and clearing Treeview node's data and then, we are calling our main function ‘LoadDirectory’.

private void btnLoadDirectory_Click(object sender, EventArgs e)  
{  
    // Setting Inital Value of Progress Bar  
    progressBar1.Value = 0;  
    // Clear All Nodes if Already Exists  
    treeView1.Nodes.Clear();  
    toolTip1.ShowAlways = true;  
    if (txtDirectoryPath.Text = "" && Directory.Exists(txtDirectoryPath.Text))  
        LoadDirectory(txtDirectoryPath.Text);  
    else  
        MessageBox.Show("Select Directory!!");  
} 

In this function, we are passing a root directory path which we are getting from the textbox in function parameter and loading sub directories of the given path and creating nodes for the each respective directory, as shown in the below code. 

public void LoadDirectory(string Dir)  
{  
    DirectoryInfo di = new DirectoryInfo(Dir);  
    //Setting ProgressBar Maximum Value  
    progressBar1.Maximum = Directory.GetFiles(Dir, "*.*", SearchOption.AllDirectories).Length + Directory.GetDirectories(Dir, "**", SearchOption.AllDirectories).Length;  
    TreeNode tds = treeView1.Nodes.Add(di.Name);  
    tds.Tag = di.FullName;  
    tds.StateImageIndex = 0;  
    LoadFiles(Dir, tds);  
    LoadSubDirectories(Dir, tds);  
}

In this function, we are passing a directory path in function parameter and loading sub directories of the given path and creating nodes for the each respective directory and setting Image for the directory node, as Shown in the below Code,

private void LoadSubDirectories(string dir, TreeNode td)  
{  
    // Get all subdirectories  
    string[] subdirectoryEntries = Directory.GetDirectories(dir);  
    // Loop through them to see if they have any other subdirectories  
    foreach (string subdirectory in subdirectoryEntries)  
    {
        DirectoryInfo di = new DirectoryInfo(subdirectory);  
        TreeNode tds = td.Nodes.Add(di.Name);  
        tds.StateImageIndex = 0;  
        tds.Tag = di.FullName;  
        LoadFiles(subdirectory, tds);  
        LoadSubDirectories(subdirectory, tds);  
        UpdateProgress();
    }  
}

In this function we are passing a directory path in function parameter and loading files of the given path and creating nodes for the each respective file and setting Image for the file node, as Shown in the below Code,  

private void LoadFiles(string dir, TreeNode td)  
{  
    string[] Files = Directory.GetFiles(dir, "*.*");  
    // Loop through them to see files  
    foreach (string file in Files)  
    {  
        FileInfo fi = new FileInfo(file);  
        TreeNode tds = td.Nodes.Add(fi.Name);  
        tds.Tag = fi.FullName;  
        tds.StateImageIndex = 1;  
        UpdateProgress();
    }  
}

In ‘UpdateProgress’ function we are simply increasing the progressbar value and on the basis of current progressbar value and maximum value we are displaying the total progress in percentage.

private void UpdateProgress()  
{  
    if (progressBar1.Value < progressBar1.Maximum)  
    {  
        progressBar1.Value++;  
        int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);  
        progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        Application.DoEvents();  
    }  
} 

Code for the Mouse Move event, here we are applying tooltip to each TreeView node, first we are finding the exact location of mouse and on the basis of location of TreeView we are finding the TreeNode, and displaying the TreeNode Tag data in tooltip.

private void treeView1_MouseMove(object sender, MouseEventArgs e)  
{  
    // Get the node at the current mouse pointer location.  
    TreeNode theNode = this.treeView1.GetNodeAt(e.X, e.Y);  
  
    // Set a ToolTip only if the mouse pointer is actually paused on a node.  
    if (theNode != null && theNode.Tag != null)  
    {  
        // Change the ToolTip only if the pointer moved to a new node.  
        if (theNode.Tag.ToString() != this.toolTip1.GetToolTip(this.treeView1))  
            this.toolTip1.SetToolTip(this.treeView1, theNode.Tag.ToString());  
    }  
    else     // Pointer is not over a node so clear the ToolTip.  
    {  
        this.toolTip1.SetToolTip(this.treeView1, "");  
    }  
}

Output

Conclusion

By using these easy methods, we can load a particular directory data in TreeView. These simple tips may help beginner level readers to understand the concepts of TreeView and TreeNodes and also there is no direct option to display tooltip for each node in TreeView so here you will get the easiest method of tooltip for Treeview Nodes. And also you can display image icon in TreeNode.

Hope this will help you and you like this article.

Please give your valuable feedback in the comment section.


Similar Articles