C# – Method to get all files within folder and subfolders that will return a list

cdirectoryfilemethodsrecursion

I have a method that will iterate through a folder and all of its subfolders and get a list of the file paths. However, I could only figure out how to create it and add the files to a public List, but not how to return the list. Here's the method:

public List<String> files = new List<String>();

private void DirSearch(string sDir)
    {
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                files.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                DirSearch(d);
            }
        }
        catch (System.Exception excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    }

So, i just call DirSearch() at some point in my code and it 'fills' the list with the paths, but I want to be able to use it multiple times to create different lists with different directories, etc.

Best Answer

You can use Directory.GetFiles to replace your method.

 Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)