界面设计:
从工具箱中拖放一个TreeView(teeView1)和一个Button(button1)到WinForm窗体中
添加引用:
using System.Threading;
using System.IO;
详细代码:
#region 目录树委托定义
private delegate void UpdateTreeViewDelegate(TreeNode node);//声明委托类型
private static string CurrentFolderPath;
#endregion
#region 目录树节点操作函数
/// <summary>
/// 加载节点到TreeView中
/// </summary>
/// <param name="node">TreeNode</param>
private void AddToTreeView(TreeNode node)
{
treeView1.Nodes.Add(node);
treeView1.Refresh();
}
/// <summary>
/// 递归加载指定目录下的所有子目录和文件树
/// </summary>
/// <param name="reg">指定目录路径</param>
/// <param name="nodes">起始树,将在它下面建立所有子结点</param>
internal void LoadFolderFileList(string path, TreeNode nodes)
{
string[] dirs = Directory.GetDirectories(path);
string[] files = Directory.GetFiles(path);
for (int i = 0; i < dirs.Length; i++)
{
string[] info = new string[4];
DirectoryInfo di = new DirectoryInfo(dirs[i]);
TreeNode node = new TreeNode(di.Name);
node.Tag = di.FullName;
try
{
if (di.GetDirectories().Length > 0 || di.GetFiles().Length > 0)
{
LoadFolderFileList(di.FullName, node);
}
else
{
continue;
}
}
catch
{
continue;
}
nodes.Nodes.Add(node);
}
for (int i = 0; i < files.Length; i++)
{
FileInfo fi = new FileInfo(files[i]);
TreeNode node = new TreeNode(fi.Name);
node.Tag=fi.FullName;
nodes.Nodes.Add(node);
}
}
#endregion