RyanWilliamWest
RyanWilliamWest

Reputation: 126

C# Enumerate Files 2 folders down using Directory.GetDirectories()

Using the EnumerateDirectories how do you enumerate only 2 folder structures down. Example: If I start at C:\, how do I get the folders inside of C as well as one additional level down?

The only thing that Directory.GetDirectories() offers so far is the SearchOption of

SearchOption.AllDirectories || SearchOption.TopDirectoryOnly

This is what I have so far:

private static List<string> GetDirectories(string path, string searchPattern = "*")
    {
        try
        {
            return Directory.GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly).ToList();
        }
        catch (UnauthorizedAccessException)
        {
            return new List<string>();
        }
    }

Upvotes: 0

Views: 614

Answers (2)

ispiro
ispiro

Reputation: 27743

You use a counter for the level and call the method recursively.

Untested code:

private static List<string> GetDirectories(string path, int level, string searchPattern = "*")
{
    if (level == 0)
        return Directory.GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly).ToList();
    else
    {
        List<string> l = new List<string>();
        foreach (string path2 in Directory.GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly))
            l.AddRange(GetDirectories(path2, level - 1, searchPattern));
        return l;
    }
}

and call like this:

return GetDirectories(yourPath, 1, yourSearchPattern);

or you can change this to drill down, then go back up for the next etc. but still using a counter.

If you need the files (though the body of your question didn't mention that, only the title), just iterate over the result, getting the files in each of the folders you got.

Upvotes: 1

Rob Stewart
Rob Stewart

Reputation: 463

You could do something like this, you'll just need to add some code if you're not authorized to access the directory.

                    Directory.GetDirectories(path, searchPattern).ToList().ForEach(
                    d =>
                    {
                        try
                        {
                            searchItems.Add(d);
                            searchItems.AddRange(Directory.GetDirectories(d, searchPattern, SearchOption.TopDirectoryOnly));
                        }
                        catch (UnauthorizedAccessException)
                        {
                            //do something when you are not authorized
                        }
                    });

Upvotes: 0

Related Questions