C# -- 使用遞歸列出文件夾目錄及目錄下的文件


使用遞歸列出文件夾目錄及目錄的下文件

1.使用遞歸列出文件夾目錄及目錄下文件,並將文件目錄結構在TreeView控件中顯示出來。

新建一個WinForm應用程序,放置一個TreeView控件:

 

代碼實現:在Form_load的時候,調用遞歸方法加載文件目錄結構在TreeView控件中

 1         private void Form1_Load(object sender, EventArgs e)
 2         {
 3             //文件夾路徑
 4             string path = "D:\\Notepad++";
 5 
 6             //TreeView根節點
 7             TreeNode node = treeView1.Nodes.Add(path);
 8 
 9             //調用遞歸
10             DirectoryToTree(path, node.Nodes);
11 
12         }
13 
14         //遞歸加載文件夾目錄及目錄下文件
15         private void DirectoryToTree(string path, TreeNodeCollection nodes)
16         {
17             foreach (string item in Directory.GetDirectories(path))
18             {
19                 TreeNode node = nodes.Add(Path.GetFileName(item));
20                 DirectoryToTree(item, node.Nodes);
21             }
22             string[] strFiles = Directory.GetFiles(path);
23             foreach (string str in strFiles)
24             {
25                 nodes.Add(Path.GetFileName(str));
26             }
27         }

 

2.運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM