[转] C#2010 在TreeView控件下显示路径下所有文件和文件夹

C#2010学习过程中有所收获,便总结下来,希望能给和我一样在学习遇到困难的同学提供参考。

本文主要介绍两个自定义函数,实现的功能是遍历路径下文件和文件夹并显示在TreeView控件中。
 
首先添加命名空间:
using System.Windows.Forms;
using System.IO;
 
函数代码如下:
 
#region 生成程序所在根目录的TreeView
        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()");
            }
        }
        #endregion
 
        #region 遍历TreeView根节点下文件和文件夹
        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;
        }
        #endregion

 

 
在Form1_Load中直接调用PaintTreeView函数,并赋参数就可以了。其中,此处fullPath为程序所在路径,可自行定义
 
程序调用显示效果如下如所示:
 
posted @ 2016-07-26 21:23  wenglabs  阅读(2511)  评论(0编辑  收藏  举报