使用TreeView控件显示磁盘文件

来源:互联网 发布:雷欧奥特曼mac 编辑:程序博客网 时间:2024/05/08 21:04
using System;using System.Windows.Forms;using System.IO;namespace WindowsFormsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            //搞个根节点            TreeNode tn1 = new TreeNode("F:\\C#例程");            //传入路径和根节点            method(@"F:\C#例程", tn1);            //把根节点挂树上            treeView1.Nodes.Add(tn1);        }        void method(string path, TreeNode tn)        {            //在指定的路径中初始化DirectoryInfo类的新实例            DirectoryInfo dir = new DirectoryInfo(path);            //遍历目录中的所有文件夹和文件            foreach (var item in dir.GetFileSystemInfos())            {                //如果是文件夹                if (Directory.Exists(item.FullName))                {                    //搞个子节点                    TreeNode tn2 = new TreeNode(item.Name);                    //把子节点加到根节点中                    tn.Nodes.Add(tn2);                    //递归                    method(item.FullName, tn2);                }                //如果是文件                else                {                    //把文件名加到根节点中                    tn.Nodes.Add(item.Name);                }            }        }    }}

0 0
原创粉丝点击