Recurse search a directory - CSharp File IO

CSharp examples for File IO:Directory

Description

Recurse search a directory

Demo Code


using System.Collections.Generic;

public class Main{
        public static IEnumerable<DirectoryAndFiles> Recurse(string directory, string searchpattern)
        {/*from  w  w  w.jav a  2  s  . c  om*/
            var stack = new Stack<string>();
            stack.Push(directory);

            while (stack.Count > 0)
            {
                string cur_dir = stack.Pop();
                var cur_files = System.IO.Directory.GetFiles(cur_dir, searchpattern);

                var item = new DirectoryAndFiles(cur_dir,cur_files);
                yield return item;

                foreach (var sd in System.IO.Directory.GetDirectories(cur_dir))
                {
                    stack.Push(sd);
                }
            }
        }
}

Related Tutorials