歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C# 非遞歸遍歷所有子目錄與子文件

C# 非遞歸遍歷所有子目錄與子文件

日期:2017/3/1 10:00:15   编辑:Linux編程

非遞歸的遍歷,使用棧來存儲當前訪問結點的子節點信息,用於接下來訪問。

通過棧保存還沒有訪問的目錄結點

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

Copyright © Linux教程網 All Rights Reserved