设为首页 加入收藏

TOP

C#递归遍历子目录与子目录中的文件
2014-11-24 08:07:50 来源: 作者: 【 】 浏览:0
Tags:目录 文件

采用C#,通过指定一个路径,来递归的遍历所有的子目录以及子目录中的文件,建一个类似资源管理器的目录树


先递归的遍历所有的子目录,如果没有子目录以后,则遍历所有的当前目录下的文件


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace Directory
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


private void textBox1_TextChanged(object sender, EventArgs e)
{


}


private void button1_Click(object sender, EventArgs e)
{
this.treeView1.Nodes.Clear();
if (folderBrowserDialog1.ShowDialog()==DialogResult.OK)
{
//
string beginPath = folderBrowserDialog1.SelectedPath;
this.textBox1.Text = beginPath;


// 构造目录树
DirectoryInfo DI=new DirectoryInfo(beginPath);
TreeNode a = new TreeNode("文件");
treeView1.Nodes.Add(a);
Traverse(a, DI);
}
}


public void Traverse(TreeNode node, DirectoryInfo dir)
{
if (dir == null)
{
// 如果目录为空,则说明没有子目录,应该返回到上一层
return;
}
else
{
TreeNode treeNode = new TreeNode(dir.Name);
node.Nodes.Add(treeNode); // 添加结点
// 子目录不空,则优先遍历所有的子目录,再遍历每个子目录中的文件
DirectoryInfo[] subDir = dir.GetDirectories();
foreach (DirectoryInfo sub in subDir)
{
Traverse(treeNode, sub); // 先遍历当前目录的子目录
}


// 遍历当前目录的文件
FileInfo[] files = dir.GetFiles();
foreach (FileInfo f in files)
{
string fileName = f.Name;
TreeNode fileNode = new TreeNode(fileName);
treeNode.Nodes.Add(fileNode);
}
}
}
}
}



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C# 非递归遍历所有子目录与子文件 下一篇Linux下用/proc/stat文件来计算cp..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)
·整理了250个shell脚 (2025-12-26 07:53:29)
·HyperText Transfer (2025-12-26 07:20:48)
·半小时搞懂 HTTP、HT (2025-12-26 07:20:42)