设为首页 加入收藏

TOP

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

非递归的遍历,使用栈来存储当前访问结点的子节点信息,用于接下来访问。


通过栈保存还没有访问的目录结点


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;
using System.Collections.Generic;


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


private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog()==DialogResult.OK)
{
string path = folderBrowserDialog1.SelectedPath;
this.textBox1.Text = path;
TreeNode node=new TreeNode("文件");
this.treeView1.Nodes.Add(node);
DirectoryInfo dir=new DirectoryInfo(path);
Traverse(node,dir);
}
}


///


/// 非递归的遍历所有的子目录与文件
///

///
///
private void Traverse(TreeNode node, DirectoryInfo dir)
{
Stack stack_dir = new Stack(); // 用栈来保存没有遍历的子目录
Stack stack_node = new Stack();
DirectoryInfo currentDir = dir;
TreeNode currentNode = node;
stack_dir.Push(dir);
stack_node.Push(node);


while (stack_dir.Count != 0) // 栈不为空,说明还有子节点没有访问到
{
currentDir=stack_dir.Pop(); // 出栈,获取上一个结点
currentNode = stack_node.Pop(); // 出栈,获取上一个TreeNode


// 访问当前目录所有子目录
DirectoryInfo[] subDirs = currentDir.GetDirectories();
foreach (DirectoryInfo di in subDirs)
{
TreeNode d = new TreeNode(di.Name);
currentNode.Nodes.Add(d);
stack_node.Push(d); // 当前TreeNode结点入栈
stack_dir.Push(di); // 将子节点入栈
}


// 访问当前目录所有子文件
FileInfo[] files = currentDir.GetFiles();
foreach (FileInfo f in files)
{
// 将文件添加到结点中
TreeNode file = new TreeNode(f.Name);
currentNode.Nodes.Add(file);
}
}
}
}
}



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇shell命令的执行 下一篇C#递归遍历子目录与子目录中的文件

评论

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

·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)