本文介绍了如何将树视图中的所有文件夹添加为带有嵌套的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件夹下有一组目录.目录结构并非 100% 一致(例如,在 A 下可能有文件夹内的文件夹,但在 B 下没有).

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

我需要使用适当的嵌套绑定树视图中的所有文件夹(例如 C:\a\b 嵌套在 C:\a 下).

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?

谢谢

推荐答案

类似:

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;
}

只需在递归方法中使用 System.IO 中的 Directory.GetDirectories() 来构建节点层次结构,并将其放入 TreeView.

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

编辑 - 根据评论添加排除机制(并将表达式转换为 Linq,在这种情况下更清晰):

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;
}

这篇关于如何将树视图中的所有文件夹添加为带有嵌套的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 21:19