File System TreeView

前端 未结 5 1764
误落风尘
误落风尘 2020-11-29 10:39

Im working with file systems and I have a List<> of file objects that have the file path as a property. Basically I need to create a treeview in .NET but im struggling to

5条回答
  •  星月不相逢
    2020-11-29 11:06

        private void Form1_Load(object sender, EventArgs e)
        {
            var paths = new List
                            {
                                @"C:\WINDOWS\AppPatch\MUI\040C",
                                @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727",
                                @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI",
                                @"C:\WINDOWS\addins",
                                @"C:\WINDOWS\AppPatch",
                                @"C:\WINDOWS\AppPatch\MUI",
                                @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MUI\0409"
                            };
            treeView1.PathSeparator = @"\";
            PopulateTreeView(treeView1, paths, '\\');
        }
    
        private static void PopulateTreeView(TreeView treeView, IEnumerable paths, char pathSeparator)
        {
            TreeNode lastNode = null;
            string subPathAgg;
            foreach (string path in paths)
            {
                subPathAgg = string.Empty;
                foreach (string subPath in path.Split(pathSeparator))
                {
                    subPathAgg += subPath + pathSeparator;
                    TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);
                    if (nodes.Length == 0)
                        if (lastNode == null)
                            lastNode = treeView.Nodes.Add(subPathAgg, subPath);
                        else
                            lastNode = lastNode.Nodes.Add(subPathAgg, subPath);
                    else
                        lastNode = nodes[0];
                }
            }
        }
    

    alt text

提交回复
热议问题