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

  1. using System.Windows.Forms;  
  2. using System.IO;  
Code for the folder browse button click event.
  1. private void btnDirectoryPath_Click(object sender, EventArgs e)  
  2. {  
  3.    folderBrowserDialog1.SelectedPath = txtDirectoryPath.Text;  
  4.    DialogResult drResult = folderBrowserDialog1.ShowDialog();  
  5.    if (drResult == System.Windows.Forms.DialogResult.OK)  
  6.       txtDirectoryPath.Text = folderBrowserDialog1.SelectedPath;  
  7.   
  8. }  

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’.

  1. private void btnLoadDirectory_Click(object sender, EventArgs e)  
  2. {  
  3.             // Setting Inital Value of Progress Bar  
  4.             progressBar1.Value = 0;  
  5.             // Clear All Nodes if Already Exists  
  6.             treeView1.Nodes.Clear();  
  7.             toolTip1.ShowAlways = true;  
  8.             if (txtDirectoryPath.Text != "" && Directory.Exists(txtDirectoryPath.Text))  
  9.                 LoadDirectory(txtDirectoryPath.Text);  
  10.             else  
  11.                 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.

  1. public void LoadDirectory(string Dir)  
  2.  {  
  3.             DirectoryInfo di = new DirectoryInfo(Dir);  
  4.             //Setting ProgressBar Maximum Value  
  5.             progressBar1.Maximum = Directory.GetFiles(Dir, "*.*", SearchOption.AllDirectories).Length + Directory.GetDirectories(Dir, "**", SearchOption.AllDirectories).Length;  
  6.             TreeNode tds = treeView1.Nodes.Add(di.Name);  
  7.             tds.Tag = di.FullName;  
  8.             tds.StateImageIndex = 0;  
  9.             LoadFiles(Dir, tds);  
  10.             LoadSubDirectories(Dir, tds);  
  11.  } 

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,

  1. private void LoadSubDirectories(string dir, TreeNode td)  
  2. {  
  3.            // Get all subdirectories  
  4.            string[] subdirectoryEntries = Directory.GetDirectories(dir);  
  5.            // Loop through them to see if they have any other subdirectories  
  6.            foreach (string subdirectory in subdirectoryEntries)  
  7.            {  
  8.   
  9.                DirectoryInfo di = new DirectoryInfo(subdirectory);  
  10.                TreeNode tds = td.Nodes.Add(di.Name);  
  11.                tds.StateImageIndex = 0;  
  12.                tds.Tag = di.FullName;  
  13.                LoadFiles(subdirectory, tds);  
  14.                LoadSubDirectories(subdirectory, tds);  
  15.                UpdateProgress();  
  16.   
  17.            }  
  18.   }  
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,
  1.  private void LoadFiles(string dir, TreeNode td)  
  2. {  
  3.             string[] Files = Directory.GetFiles(dir, "*.*");  
  4.   
  5.             // Loop through them to see files  
  6.             foreach (string file in Files)  
  7.             {  
  8.                 FileInfo fi = new FileInfo(file);  
  9.                 TreeNode tds = td.Nodes.Add(fi.Name);  
  10.                 tds.Tag = fi.FullName;  
  11.                 tds.StateImageIndex = 1;  
  12.                 UpdateProgress();  
  13.   
  14.             }  
  15. }  
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.
  1. private void UpdateProgress()  
  2.   
  3.            if (progressBar1.Value < progressBar1.Maximum)  
  4.            {  
  5.                progressBar1.Value++;  
  6.                int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);  
  7.                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));  
  8.   
  9.                Application.DoEvents();  
  10.            }  
  11. }  

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.

  1. private void treeView1_MouseMove(object sender, MouseEventArgs e)  
  2.   
  3.            // Get the node at the current mouse pointer location.  
  4.            TreeNode theNode = this.treeView1.GetNodeAt(e.X, e.Y);  
  5.   
  6.            // Set a ToolTip only if the mouse pointer is actually paused on a node.  
  7.            if (theNode != null && theNode.Tag != null)  
  8.            {  
  9.                // Change the ToolTip only if the pointer moved to a new node.  
  10.                if (theNode.Tag.ToString() != this.toolTip1.GetToolTip(this.treeView1))  
  11.                    this.toolTip1.SetToolTip(this.treeView1, theNode.Tag.ToString());  
  12.   
  13.            }  
  14.            else     // Pointer is not over a node so clear the ToolTip.  
  15.            {  
  16.                this.toolTip1.SetToolTip(this.treeView1, "");  
  17.            }  
  18. }  

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.