FANDOM


To walk a directory tree, use the class DirectoryTreeTraverser. Simply derive from it, and override the HandleItem method to do whatever you want. See example below:

public abstract class DirectoryTreeTraverser
{
    abstract public void HandleItem(string file, bool isDir);

    public void Do(string root)
    {
        var directories = new Stack<string>(32);

        directories.Push(root);

        while (directories.Count > 0)
        {
            var currentDir = directories.Pop();
            HandleItem(currentDir, true);

            foreach (string file in Directory.GetFiles(currentDir))
                HandleItem(file, false);

            foreach (string directory in Directory.GetDirectories(currentDir))
                directories.Push(directory);
        }
    }
}

ExampleEdit

    public class FileLocator : DirectoryTreeTraverser
    {
        private string _substring;

        public FileLocator(string substring)
        {
            _substring = substring;
        }

        public override void HandleItem(string file, bool isDir)
        {
            if ( file.Contains( _substring ) )
                Console.WriteLine("{0}, {1}", file, isDir);
        }
    }

Calling it:Edit

            var fileLocator = new FileLocator("txt");
            fileLocator.Do(@"C:\My Stuff");

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.