使用递归列出文件夹目录及目录的下文件
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.运行结果:
