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

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

 a |_b |_c d e 

我想要一个没有主文件夹的树视图。 我在这里找到了一个解决方案,但它看起来非常慢。 当我第一次启动程序时,加载它需要一分钟。 没有该代码,它立即打开。

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

编辑: 解决了

试试这个,它在这里看起来很快。 您可以控制是否扩展所有节点。您需要包含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 getFolderNodes(string dir, bool expanded) { var dirs = Directory.GetDirectories(dir).ToArray(); var nodes = new List(); 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代码:

 List getAllFolderNodes(string dir) { var dirs = Directory.GetDirectories(dir).ToArray(); var nodes = new List(); 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;