Reputation: 527
I would like an algorithm which generates a file structure starting from a user specified directory, but have it only show a specific type of file (.resx). So far I have the code below, which shows the file structure and displays only .resx files, but the problem is that it shows all of the directories which do not contain a .resx file as well. i.e. if a treeviewitem or any of its children does not contain a .resx file, it should not be there.
void DirSearch(string sDir, TreeViewItem parentItem)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
TreeViewItem item = new TreeViewItem();
item.Header = d;
parentItem.Items.Add(item);
foreach (string f in Directory.GetFiles(d, "*.resx"))
{
TreeViewItem subitem = new TreeViewItem();
subitem.Header = f;
subitem.Tag = f;
item.Items.Add(subitem);
}
DirSearch(d, item);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
Upvotes: 1
Views: 46
Reputation:
Add the TreeViewItem representing a directory to its parent only if it has children (*.resx files, or sub-directories containing *.resx files). Note that DirSearch is called recursively before that check is being made.
void DirSearch(string sDir, TreeViewItem parentItem)
{
......
foreach (string d in Directory.GetDirectories(sDir))
{
TreeViewItem item = new TreeViewItem();
item.Header = d;
foreach (string f in Directory.GetFiles(d, "*.resx"))
{
TreeViewItem subitem = new TreeViewItem();
subitem.Header = f;
subitem.Tag = f;
item.Items.Add(subitem);
}
DirSearch(d, item);
if (item.Items.Count > 0)
parentItem.Items.Add(item);
}
......
}
Upvotes: 1