递归遍历文件夹,并添加到TreeView控件中
生活随笔
收集整理的這篇文章主要介紹了
递归遍历文件夹,并添加到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
總結
以上是生活随笔為你收集整理的递归遍历文件夹,并添加到TreeView控件中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Provisioning profile
- 下一篇: hdu 4268 Alice and B