TreeView控件下显示路径下所有文件和文件夹

本文主要介绍两个自定义函数,实现的功能是遍历路径下文件和文件夹并显示在TreeView控件中。

首先添加命名空间:
using System.Windows.Forms;
using System.IO;

函数代码如下:

 private void PaintTreeView(TreeView treeView, string fullPath)
    {
        try
        {
            treeView.Nodes.Clear(); //清空TreeView
 
            DirectoryInfo dirs = new DirectoryInfo(fullPath); //获得程序所在路径的目录对象
            DirectoryInfo[] dir = dirs.GetDirectories();//获得目录下文件夹对象
            FileInfo[] file = dirs.GetFiles();//获得目录下文件对象
            int dircount = dir.Count();//获得文件夹对象数量
            int filecount = file.Count();//获得文件对象数量
 
            //循环文件夹
            for (int i = 0; i < dircount; i++)
            {
                treeView.Nodes.Add(dir[i].Name);
                string pathNode = fullPath + "\\" + dir[i].Name;
                GetMultiNode(treeView.Nodes[i], pathNode);
            }
 
            //循环文件
            for (int j = 0; j < filecount; j++)
            {
                treeView.Nodes.Add(file[j].Name);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + "\r\n出错的位置为:Form1.PaintTreeView()");
        }
    }

 
    private bool GetMultiNode(TreeNode treeNode, string path)
    {
        if (Directory.Exists(path) == false)
        { return false; }
 
        DirectoryInfo dirs = new DirectoryInfo(path); //获得程序所在路径的目录对象
        DirectoryInfo[] dir = dirs.GetDirectories();//获得目录下文件夹对象
        FileInfo[] file = dirs.GetFiles();//获得目录下文件对象
        int dircount = dir.Count();//获得文件夹对象数量
        int filecount = file.Count();//获得文件对象数量
        int sumcount = dircount + filecount;
 
        if (sumcount == 0)
        { return false; }
 
        //循环文件夹
        for (int j = 0; j < dircount; j++)
        {
            treeNode.Nodes.Add(dir[j].Name);
            string pathNodeB = path + "\\" + dir[j].Name;
            GetMultiNode(treeNode.Nodes[j], pathNodeB);
        }
 
        //循环文件
        for (int j = 0; j < filecount; j++)
        {
            treeNode.Nodes.Add(file[j].Name);
        }
        return true;
    }

在Form1_Load中直接调用PaintTreeView函数,并赋参数就可以了。其中,此处fullPath为程序所在路径,可自行定义。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值