C#获取磁盘目录结构并显示TreeView控件中续集1

时间:2022-06-24 12:39:18

经过改正,现在进步一步更新的代码贴出来:

 //窗体初始化时,在树控件中添加“我的电脑”节点
        private void Form1_Load(object sender, EventArgs e)
        {
            TreeNode TNode = new TreeNode("我的电脑");
            tvMenu.Nodes.Add(TNode);
        }


        //选择树控件节点时,显示该节点下的所有文件夹及文件名(以全路径格式显示)
        private void tvMenu_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TVShow(e.Node);
        }

public void TVShow(TreeNode TNode)
        {
            try
            {
                if (TNode.Nodes.Count == 0)
                {
                    if (TNode.Parent == null)
                    {
                        foreach (string DirName in Directory.GetLogicalDrives())
                        {
                            TreeNode DirNode = new TreeNode(DirName);
                            DirNode.Tag = DirName;
                            TNode.Nodes.Add(DirNode);
                        }
                    }
                    else
                    {
                        foreach (string PathName in Directory.GetFileSystemEntries((string)TNode.Tag))
                        {
                            TreeNode PathNode = new TreeNode(PathName);
                            PathNode.Tag = PathName;
                            TNode.Nodes.Add(PathNode);
                        }
                    }
                }
            }
            catch { }
        }