GurdeepS
GurdeepS

Reputation: 67213

How to add all folders in a treeview as nodes with nesting

I have a set of directories under a folder. The directory structure isn't 100% consistent (e.g. under A there maybe folders within folders but not under B).

I need to bind all the folders in a treeview with appropriate nesting (e.g. C:\a\b nests under C:\a).

Is there an easy way, or even free treeview, that would let me do this?

Thanks

Upvotes: 3

Views: 4247

Answers (1)

Chris Ballard
Chris Ballard

Reputation: 3769

Something like:

private void Form_Load(object sender, EventArgs e)
{
    treeView.Nodes.Add(GetDirectoryNodes(@"C:\TEST"));
}

private static TreeNode GetDirectoryNodes(string path)
{
    var node = new TreeNode(path);

    var subDirs = Directory.GetDirectories(path).Select(d => GetDirectoryNodes(d)).ToArray();
    node.Nodes.AddRange(subDirs);

    return node;
}

Just uses Directory.GetDirectories() from System.IO in a recursive method to build the node hierarchy, and drop this into the TreeView.

EDIT - adding exclusion mechanism as per comments (and converted expression to Linq, which is clearer in this case):

private void Form_Load(object sender, EventArgs e)
{
    treeView.Nodes.Add(GetDirectoryNodes(@"C:\TEST", new string[] { @"C:\TeST\C", @"C:\TEST\E" }));
}

private static TreeNode GetDirectoryNodes(string path, string[] exclusions)
{
    var node = new TreeNode(Path.GetFileName(path));

    var subDirs = (from d in Directory.GetDirectories(path)
                   where !exclusions.Contains(d,StringComparer.CurrentCultureIgnoreCase)
                   select GetDirectoryNodes(d,exclusions)).ToArray();

    node.Nodes.AddRange(subDirs);
    return node;
}

Upvotes: 4

Related Questions