使用TreeView控件显示磁盘文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32832727/article/details/54696113
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);
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_32832727/article/details/54696113