递归遍历文件夹,并添加到TreeView控件中

 

遍历文件夹,并把所有节点增加到TreeView控件中,这里单独写成了一个静态类,传入根目录节点和指定的目录这两个参数即可,可以稍作扩展用于其他方案

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO;
 6 
 7 namespace 文件和文件夹遍历
 8 {
 9     public static class RecursionDirectory
10     {
11         /// <summary>
12         /// 递归遍历文件夹,并载入到Treeview的node节点
13         /// </summary>
14         /// <param name="parantNode">需要装载的父节点</param>
15         /// <param name="parantPath">需要装载的父目录</param>
16         public static void GetTreeNode(System.Windows.Forms.TreeNode parantNode, string parantPath)
17         {
18 
19             try
20             {
21                 //获取目录中的文件夹和文件
22                 string[] dirs = Directory.GetDirectories(parantPath);
23                 string[] fileNames = Directory.GetFiles(parantPath);
24 
25                 //装载目录
26                 if (dirs.Length > 0)
27                 {
28                     foreach (string item in dirs)
29                     {
30                         System.Windows.Forms.TreeNode tn = new System.Windows.Forms.TreeNode(Path.GetFileName(item));
31                         tn.Name = item;
32                         //递归遍历
33                         GetTreeNode(tn, item);
34 
35                         parantNode.Nodes.Add(tn);
36                     }
37                 }
38 
39                 //装载文件
40                 if (fileNames.Length > 0)
41                 {
42                     foreach (string item in fileNames)
43                     {
44                         System.Windows.Forms.TreeNode tn = new System.Windows.Forms.TreeNode(Path.GetFileName(item));
45                         tn.Name = item;
46                         parantNode.Nodes.Add(tn);
47                     }
48                 }
49             }
50             catch (Exception ex)
51             {
52 
53                 throw ex;
54             }
55 
56 
57         }
58     }
59 }

目前还不能很好地处理无权限访问的文件夹,特别是受系统系统保护的隐藏文件夹。

 

 

 

转载于:https://www.cnblogs.com/davy2495/archive/2012/09/08/2676671.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值