/// <summary> /// 非递归遍历文件夹 /// </summary> public class UnRecursionDirectoryReader { public event UnRecursionRead OnUnRecursionItemRead; public event UnRecursionRead OnUnRecursionDequeue; public event UnRecursionRead OnUnRecursionEnqueue;
public void Read(string Path) { string P_Path = Path; Queue<string> source = new Queue<string>(); bool IsHasChild = true;//是否有子文件夹 while (IsHasChild) { string[] Directorys = System.IO.Directory.GetDirectories(P_Path); string[] Files = System.IO.Directory.GetFiles(P_Path); foreach (string dir in Directorys) { source.Enqueue(dir); //入队列,开始访问文件夹 if (OnUnRecursionEnqueue != null) OnUnRecursionEnqueue(dir, P_Path); } foreach (string file in Files) { if (OnUnRecursionItemRead != null) OnUnRecursionItemRead(file, P_Path); //访问文件 } if (source.Count > 0) { string OldPath = P_Path; P_Path = source.Dequeue();//出队列,更换文件夹 if (OnUnRecursionDequeue != null) OnUnRecursionDequeue(P_Path, OldPath); } else { IsHasChild = false; } } } }
demo:
TreeNode TargetNode = null; //指向treeview的结点 Queue<TreeNode> TreeQueue = new Queue<TreeNode>(); //临时存放
private void read() { CYS.UnRecursionDirectoryReader TreeReader = new CYS.UnRecursionDirectoryReader(); TreeReader.OnUnRecursionDequeue+=new CYS.UnRecursionRead(TreeReader_OnUnRecursionDequeue); TreeReader.OnUnRecursionEnqueue+=new CYS.UnRecursionRead(TreeReader_OnUnRecursionEnqueue); TreeReader.OnUnRecursionItemRead+=new CYS.UnRecursionRead(TreeReader_OnUnRecursionItemRead); TreeReader.Read(AppRoot); }
private void TreeReader_OnUnRecursionItemRead(string DireName, string Parent) { TargetNode.Nodes.Add(System.IO.Path.GetFileName(DireName)); }
private void TreeReader_OnUnRecursionDequeue(string DireName, string Parent) { TargetNode = TreeQueue.Dequeue(); }
private void TreeReader_OnUnRecursionEnqueue(string DireName, string Parent) { TreeNode Node = new TreeNode(System.IO.Path.GetFileName(DireName)); TargetNode.Nodes.Add(Node); TreeQueue.Enqueue(Node); }
|