用TreeView控件遍历磁盘目录

时间:2022-06-28 12:41:01

实现效果:

  用TreeView控件遍历磁盘目录

知识运用:

  ListView控件中Items集合的Add方法  TteeView控件中Nodes集合的Add方法

实现代码:

        private void Form1_Load(object sender, EventArgs e)
        {
            TreeNode rootNode = new TreeNode("我的电脑");
            treeView1.Nodes.Add(rootNode);
        }

        private void ListViewShow(TreeNode NodeDir) {
            listViewFile.Clear();
            try
            {
                if (NodeDir.Parent == null)
                {
                    foreach (string DrvName in Directory.GetLogicalDrives())
                    {
                        ListViewItem ItemList = new ListViewItem(DrvName);
                        listViewFile.Items.Add(ItemList);
                    }
                }
                else
                {
                    foreach (string dirName in Directory.GetDirectories((string)NodeDir.Tag))
                    {
                        ListViewItem dirItem = new ListViewItem(dirName);
                        listViewFile.Items.Add(dirItem);
                    }
                    foreach (string fileName in Directory.GetFiles((string)NodeDir.Tag))
                    {
                        ListViewItem fileItem = new ListViewItem(fileName);
                        listViewFile.Items.Add(fileItem);
                    }
                }
            }
            catch { }
        }
        
        private void TreeViewShow(TreeNode selectNode) {
            try { 
               if(selectNode.Nodes.Count==0){
                   if (selectNode.Parent == null)
                   {
                       foreach (string drvName in Directory.GetLogicalDrives())
                       {
                           TreeNode drvNode = new TreeNode(drvName);
                           drvNode.Tag = drvName;
                           selectNode.Nodes.Add(drvNode);
                       }
                   }
                   else {
                       foreach (string dirName in Directory.GetDirectories((string)selectNode.Tag))
                       {
                           TreeNode dirNode = new TreeNode(dirName);
                           dirNode.Tag = dirName;
                           selectNode.Nodes.Add(dirNode);
                       }
                   }
               }
            }catch(Exception ex){
                MessageBox.Show(ex.Message);
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeViewShow(e.Node);
            ListViewShow(e.Node);
        }