C#如何使用treeView列出目录和子目录而不显示根目录?

问题描述:

来自

main folder
|_a
| |_b
| |_c
|_d
|_e

a
 |_b
 |_c
d
e

我想要一个没有主文件夹的树状视图.我找到了一个解决方案 在这里,但它似乎非常慢.当我第一次启动程序时,加载它需要一分钟多的时间.如果没有该代码,它会立即打开.

I want a treeview without the main folder. I found a solution here but it seems that it's incredibly slow. When I first start the program it takes over a minute to load it. Without that code it opens instantly.

那么,您知道为什么要改进此代码或其他更好的代码吗?

So, do you know any why to improve this code or another better code?

已解决.

试试这个,这里看起来真的很快.您可以控制是否扩展所有节点..您需要包含 LINQ namspace (using System.Linq;)

Try this, it looks real fast here. You can control whether all nodes are expanded or not.. You need to included the LINQ namspace (using System.Linq;)

// somewhere:
string yourRoot = "D:\\";
treeView1.Nodes.AddRange(getFolderNodes(yourRoot, true).ToArray());

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    TreeNode tn = e.Node.Nodes[0];
    if (tn.Text == "...")
    {
        e.Node.Nodes.AddRange(getFolderNodes(((DirectoryInfo)e.Node.Tag)
              .FullName, true).ToArray());
        if (tn.Text == "...") tn.Parent.Nodes.Remove(tn);
    }
}

List<TreeNode> getFolderNodes(string dir, bool expanded)
{
    var dirs = Directory.GetDirectories(dir).ToArray();
    var nodes = new List<TreeNode>();
    foreach (string d in dirs)
    {
        DirectoryInfo di = new DirectoryInfo(d);
        TreeNode tn = new TreeNode(di.Name);
        tn.Tag = di;
        int subCount = 0;
        try { subCount = Directory.GetDirectories(d).Count();  } 
        catch { /* ignore accessdenied */  }
        if (subCount > 0) tn.Nodes.Add("...");
        if (expanded) tn.Expand();   //  **
        nodes.Add(tn);
    }
    return nodes;
}

如果你确定你总是想从一开始就看到所有级别的展开,你可以使用这个功能并删除BeforeExpand代码:

If you are sure you always want to see all levels expaded from the start you can use this function and delete the BeforeExpand code:

List<TreeNode> getAllFolderNodes(string dir)
{
    var dirs = Directory.GetDirectories(dir).ToArray();
    var nodes = new List<TreeNode>();
    foreach (string d in dirs)
    {
        DirectoryInfo di = new DirectoryInfo(d);
        TreeNode tn = new TreeNode(di.Name);
        tn.Tag = di;
        int subCount = 0;
        try { subCount = Directory.GetDirectories(d).Count(); } 
        catch { /* ignore accessdenied */  }
        if (subCount > 0)
        {
            var subNodes = getAllFolderNodes(di.FullName);
            tn.Nodes.AddRange(subNodes.ToArray());
        }
        nodes.Add(tn);
    }
    return nodes;
}

你像以前一样称呼它:

string yourRoot = "D:\\";
Cursor.Current = Cursors.WaitCursor;
treeView1.Nodes.AddRange(getAllFolderNodes(yourRoot).ToArray());
Cursor.Current = Cursors.Default;