Search code examples
c#.netvisual-studio-2010filedirectory

List of all folders and files for x depth


I want to have list of all folders and files for x depth.

If x is 2 than I will have information about all folders and files from first folder, and all folders and files from folders in first folder.

How to do this?


Solution

  • This code will do what other answers are doing, but also return the folder names (as that appears to be part of what you are asking). This will require .Net 4.0. If you wish to keep track of which are folders and which are files you could return a tuple containing a list of files and a list of folders.

    List<string> GetFilesAndFolders(string root, int depth)
    {
        var list = new List<string>();
        foreach(var directory in Directory.EnumerateDirectories(root))
        {
            list.Add(directory);
            if (depth > 0)
            {
                list.AddRange(GetFilesAndFolders(directory, depth-1));
            }
        }
    
        list.AddRange(Directory.EnumerateFiles(root));
    
        return list;
    }
    

    EDIT: Code that keeps the folders and files separate

    Tuple<List<string>,List<string>> GetFilesAndFolders(string root, int depth)
    {
        var folders = new List<string>();
        var files = new List<string>();
        foreach(var directory in Directory.EnumerateDirectories(root))
        {
            folders.Add(directory);
            if (depth > 0)
            {
                    var result = GetFilesAndFolders(directory, depth-1);
                    folders.AddRange(result.Item1);
                    files.AddRange(result.Item2);
            }
        }
    
        files.AddRange(Directory.EnumerateFiles(root));
    
        return new Tuple<List<string>,List<string>>(folders, files);
    }