0

I've created the solution below to return all filepaths, but it does only seem to work for one folder. Any suggestions what I'm doing wrong?

    public static List<string> GetFilePaths(string dir)
    {
        var dirs = Directory.GetDirectories(dir);
        if (dirs.Count() > 0)
        {
            foreach (var pwd in dirs)
            {
                return GetFilePaths(pwd).ToList();
            }
        }

        return Directory.GetFiles(dir).ToList();
    }
Peter
  • 31
  • 3
  • 1
    Any reason not to use [`Directory.EnumerateFiles`](https://msdn.microsoft.com/en-us/library/dd383571(v=vs.110).aspx)? Simply `Directory.EnumerateFiles(path, "*.*", SearchOptions.AllDirectories)` – Yuval Itzchakov Jan 01 '16 at 15:03
  • 2
    Are you aware that GetDirectories as well GetFiles have overloads that allows you to search subfolders and makes all this recursive approach useless? – Steve Jan 01 '16 at 15:04

3 Answers3

2

You are using return after each iteration of the loop. That will cause the function to return in the very first iteration and the rest of it will become useless. Instead declare a List in the beginning and then keep adding to it and finally return it.

public static List<string> GetFilePaths(string dir)
{
    var result = new List<string>;
    var dirs = Directory.GetDirectories(dir);
    if (dirs.Count() > 0)
    {
        foreach (var pwd in dirs)
        {
            result.AddRange(GetFilePaths(pwd));
        }
    }

    result.AddRange(GetFilePaths(dir));
    return result;
}
Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
0

You're returning from the loop in it's first iteration. You should either accumulate your results in some sort of a variable:

var filePaths = new List<string>();
foreach (var subDir in Directory.GetDirectories(dir))
{
    filePaths.AddRange(GetFilePaths(subDir);
}

or use LINQ:

var filePaths = Directory.GetDirectories(dir).SelectMany(s => GetFilePaths(s));
Tamas Czinege
  • 118,853
  • 40
  • 150
  • 176
0

You should populate list for every folder.

public static List<string> GetFilePaths(string dir)
{
    var dirs = Directory.GetDirectories(dir);
    var returnList = new List<string>();

    if (dirs.Count() > 0)
    {
        foreach (var pwd in dirs)
        {
            returnList.AddRange(GetFilePaths(pwd));
        }
    }

    returnList.AddRange(Directory.GetFiles(dir));
    return returnList;
}
Valentin
  • 5,380
  • 2
  • 24
  • 38