遍历文件夹,并把所有节点增加到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 }
目前还不能很好地处理无权限访问的文件夹,特别是受系统系统保护的隐藏文件夹。