日期:2014-05-17  浏览次数:20884 次

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;
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);
            }
        }

        /// <summary>
        /// 非递归的遍历所有的子目录与文件
        /// </summary>
        /// <param name="node"></param>
        /// <param name="dir"></param>
        private void Traverse(TreeNode node, DirectoryInfo dir)
        {
            Stack<DirectoryInfo> stack_dir = new Stack<DirectoryInfo>(); // 用栈来保存没有遍历的子目录
            Stack<TreeNode> stack_node = new Stack<TreeNode>();
            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);
                }
            }
        }
    }
}