'How to remove sub folders without any files then parent folders if their sub folders and themselves do not contain any files
I have a slightly modified codes to populate my treeView1 with only .PDF files. It works well, except it leaves with many empty folders. Is it a way to remove these folders?
private void Begin()
{
treeView1.Nodes.Clear();
if (Directory.Exists(FilePath))
LoadDirectory(FilePath);
}
public void LoadDirectory(string Dir)
{
DirectoryInfo di = new DirectoryInfo(Dir);
TreeNode tds = treeView1.Nodes.Add(di.Name);
tds.Tag = di.FullName;
tds.StateImageIndex = 0;
LoadFiles(Dir, tds);
LoadSubDirectories(Dir, tds);
}
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);
}
}
private void LoadFiles(string dir, TreeNode td)
{
string[] Files = Directory.GetFiles(dir, "*.PDF");
// 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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
