本文主要介绍两个自定义函数,实现的功能是遍历路径下文件和文件夹并显示在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为程序所在路径,可自行定义。