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 thoughts on “C#: Recursively get all files in a folder and its subfolders”

  1. If you use the overload with three parameters (the third parameter is the search option), you can recursively search through all subdirectories with a single method.

    foreach(string file in Directory.GetFiles(filePath,”*.*”, SearchOption.AllDirectories))
    {
    //Do something here with filePath
    }

    1. Ah, you’re right, thanks! It seems the MS article I was referencing is very out of date, given it talks about VS 2005 and 2008. Your approach was introduced in .NET 2.0, which admittedly now is quite prehistoric, yet the MS article is still ranking quite high in Google results. I am now changing the post to reflect this overload…

  2. Thanks for your posts! I’m a regular visitor and am doing very similar work… honeybee work flows etc… I always find your explanations clear and helpful!

    1. Thanks for your feedback – it’s great to hear! If there’s anything else I can write about that would be helpful to you and the wider community, I’m always open to suggestions.

  3. Great article, I was searching for this in need for some CLR coding in SQL.
    There is a slight flaw in the alternative way.
    The routine gives double filenames.
    This fixes that problem:

    private void getFilesRecursive(string sDir)
    {
    var names = new List();
    try
    {
    foreach (string d in Directory.GetDirectories(sDir))
    {
    getFilesRecursive(d);
    }
    foreach (var file in Directory.GetFiles(sDir))
    DoAction(file);
    }
    catch (System.Exception e)
    {
    MessageBox.Show(e.Message);
    }
    }

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: