C#: Recursively get all files in a folder and its subfolders

How to recursively get all files in a folder, including files contained within subfolders.

Or, in other words, how to find every file contained within a parent folder, and within any folders inside the parent folder.

The easy way

There is a method built into .NET, though it is buried as an overload, so you may not have known it was there until someone points it out to you…

foreach (string file in System.IO.Directory.GetFiles(
    parentDirectory, "*",SearchOption.AllDirectories))
{
    //do something with file
}

This loops through every file contained within the folder, including all files contained within any subfolders. Each loop returns a string of the address of each file.

The second parameter is a search filter. The value above of "*" simply means “return anything”. We could filter for Word documents by changing this to "*.docx", for example.

The alternative way

Microsoft offered a solution of their own in this old article, which provides an interesting iterative approach.

I have modified the above method slightly to also include files immediately within the parent directory. Microsoft’s solution currently doesn’t do this

The code below adds all filepaths to a List. If you wish to do something else, you need to change what happens within DoAction(). You might actually want to give DoAction a more sensible name too, depending on what your action is.

        List<string> files = new List<string>();

        private void getFilesRecursive(string sDir)
        {
            try
            {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    getFilesRecursive(d);
                }
                foreach (var file in Directory.GetFiles(sDir))
                {
                    //This is where you would manipulate each file found, e.g.:
                    DoAction(file);
                }
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void DoAction(string filepath)
        {
            files.Add(filepath);
        }
6 Comments

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.