20.12.
2017 Display Sub Directories and Files in Treeview - CodeProject
13,304,397 members (51,474 online) Sign in
Search for articles, questions, tips
articles Q&A forums lounge
Display Sub Directories and Files in Treeview
Altaf Ansari, 4 Dec 2017
4.67 (4 votes) Rate this:
Load Directory and sub directory and files
Download source code - 65 KB
Introduction
In this tip, I am going to share with you how to Display Sub Directories and Files in Treeview in C#.
Here, we are going to learn to Display Sub directories and Files into TreeView and 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’.
https://www.codeproject.com/Tips/1219576/Display-Sub-Directories-and-Files-in-Treeview 1/7
20.12.2017 Display Sub Directories and Files in Treeview - CodeProject
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:
https://www.codeproject.com/Tips/1219576/Display-Sub-Directories-and-Files-in-Treeview 2/7
20.12.2017 Display Sub Directories and Files in Treeview - CodeProject
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, 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
Hide Copy Code
using System.Windows.Forms;
using System.IO;
Code for the folder browse button click event.
Hide Copy Code
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 resetting the progressbar value and clearing Treeview nodes
data and then we are calling our main function ‘LoadDirectory’.
Hide Copy Code
private void btnLoadDirectory_Click(object sender, EventArgs e)
{
// Setting Initial 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 each respective directory, as shown in the below code:
Hide Copy Code
// Loading Data From EXcel to DataGridView
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 each respective directory
and setting Image for the directory node, as shown in the below code:
Hide Copy 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 each respective file and setting Image
for the file node, as shown in the below code:
Hide Copy Code
private void LoadFiles(string dir, TreeNode td)
{
string[] Files = Directory.GetFiles(dir, "*.*");
// Loop through them to see files
https://www.codeproject.com/Tips/1219576/Display-Sub-Directories-and-Files-in-Treeview 3/7
20.12.2017 Display Sub Directories and Files in Treeview - CodeProject
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.
Hide Copy Code
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.
Hide Copy Code
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
https://www.codeproject.com/Tips/1219576/Display-Sub-Directories-and-Files-in-Treeview 4/7
20.12.2017 Display Sub Directories and Files in Treeview - CodeProject
Conclusion
By using these easy and simple methods, we can load a particular directory data in TreeView, these simple tips may help a beginner level reader 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 displaying image icon in TreeNode.
Hope this will help you and you would like this article.
Please give your valuable feedback in the comments section.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Share
TWITTER FACEBOOK
About the Author
https://www.codeproject.com/Tips/1219576/Display-Sub-Directories-and-Files-in-Treeview 5/7
20.12.2017 Display Sub Directories and Files in Treeview - CodeProject
Altaf Ansari
Software Developer Prothious Engineering Services
India
I am Dot Net Developer and Working on Microsoft Technology Asp.Net, C#, SQL, Windows Application, Web Application.
You may also be interested in...
Using PDFs to Manage and Share Content SAPrefs - Netscape-like Preferences Dialog
Enhanced BrowseForFolder styled TreeView Window Tabs (WndTabs) Add-In for DevStudio
Displaying XML in a WPF TreeView To Heap or not to Heap; That’s the Large Object Question?
Comments and Discussions
You must Sign In to use this message board.
Search Comments
First Prev Next
Great
Member 13560289 5-Dec-17 16:15
Display Sub Directories and Files in Treeview is great, I got somuch nice information.
Exolearn!
Sign In · View Thread
Re: Great
Altaf Ansari 5-Dec-17 18:23
Thank You...
Sign In · View Thread
Suggest not using Application.DoEvents()
Ravi Bhavnani 5-Dec-17 9:34
You'd be better off asynchronously searching for files and folders and populating the tree control via event handlers. To understand why use of
Application.DoEvents() isn't recommend, see the Caution note on this[^] MSDN page.
/ravi
https://www.codeproject.com/Tips/1219576/Display-Sub-Directories-and-Files-in-Treeview 6/7
20.12.2017 Display Sub Directories and Files in Treeview - CodeProject
My new year resolution: 2048 x 1536
Home | Articles | My .NET bits | Freeware
ravib(at)ravib(dot)com
Sign In · View Thread
Re: Suggest not using Application.DoEvents()
Altaf Ansari 5-Dec-17 22:53
Thank you for suggestion... will keep it mind in my next publish..
Sign In · View Thread
Refresh 1
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Permalink | Advertise | Privacy | Terms of Use | Mobile Layout: fixed | Article Copyright 2017 by Altaf Ansari
Sprache auswählen ▼
Web03 | 2.8.171207.1 | Last Updated 5 Dec 2017 fluid Everything else Copyright © CodeProject, 1999-2017
https://www.codeproject.com/Tips/1219576/Display-Sub-Directories-and-Files-in-Treeview 7/7