Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Folder creation

Tags:

c#

.net

recursion

Im sitting with a brain teaser that I cannot seem to complete. I am trying to create a specific folder structure. The structure is explained here:

In the root folder specified, the application should create 10 folders, '0' - '10'. Inside each of these, should again be folders '0' - '10', and etc. This must go on to a user defined level.

Using for loops, I have managed to get this so far, but can imagine that a recursive function will look a lot less messy, but melts my brain at the same time trying to figure it out D:

static void Main(string[] args)
       {
            string basePath = Path.Combine(Environment.CurrentDirectory, "Lib");

            for (int a = 0; a < 10; a++)
            {
                CreateFolders(basePath);
                basePath = Path.Combine(basePath, a.ToString());

                for (int b = 0; b < 10; b++)
                {
                    CreateFolders(basePath);
                    basePath = Path.Combine(basePath, b.ToString());

                    for (int c = 0; c < 10; c++)
                    {
                        CreateFolders(basePath);
                        basePath = Path.Combine(basePath, c.ToString());

                        for (int d = 0; d < 10; d++)
                        {
                            CreateFolders(basePath);
                            basePath = Path.Combine(basePath, d.ToString());

                            basePath = Helpers.DirMoveBack(basePath);
                        }
                        basePath = Helpers.DirMoveBack(basePath);
                    }
                    basePath = Helpers.DirMoveBack(basePath);
                }
                basePath = Helpers.DirMoveBack(basePath);
            }

            Console.ReadLine();
       }

// Creates folders '0' - '9' in the specified path
static void CreateFolders(string path)
    {
        for (int a = 0; a < 10; a++)
        {
            Directory.CreateDirectory(string.Format("{0}\\{1}", path, a));
            Console.WriteLine(string.Format("{0}\\{1}", path, a));
        }
    }


public static class Helpers
    {

        // Moves the directory back one step
        public static string DirMoveBack(string path)
        {
            for (int a = path.Length - 1; a > 0; a--)
                if (path[a] == '\\')
                    return path.Substring(0, a);

            return path;
        }
    }

As you can see, this is quite messy. If you run the code, it will create the desired folder structure, but I want it done recursively. Im trying to expand my way of thinking, and this seems to be a real brain teaser. Any help would be greatly appreciated

like image 993
Johan Aspeling Avatar asked Jan 09 '14 22:01

Johan Aspeling


People also ask

How do I create a recursive folder?

Creating Directories Recursively To create a multi-layer directory, mkdir comes with the flag -p or –parents. In this mode, mkdir will return no error if the parent directory exists. If the parent directory doesn't exist, it will create it instead.

What is a recursive folder?

What is a recursive listing of files? Recursive means that Linux or Unix command works with the contains of directories, and if a directory has subdirectories and files, the command works on those files too (recursively).

How do I create a recursive directory in Python?

makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os. makedirs() method will create them all. Suppose we want to create directory 'ihritik' but Directory 'GeeksForGeeks' and 'Authors' are unavailable in the path.


2 Answers

Yes, recursive is shorter :) A natural fit for anything that resembles a tree structure:

    static void Main(string[] args) {
        CreateFolders(3, "c:\\temp\\temp");
    }

    static void CreateFolders(int depth, string path) {
        if (depth <= 0) return;
        for (int ix = 0; ix <= 10; ++ix) {
            var dir = Path.Combine(path, ix.ToString());
            System.IO.Directory.CreateDirectory(dir);
            CreateFolders(depth - 1, dir);
        }
    }
like image 100
Hans Passant Avatar answered Oct 03 '22 22:10

Hans Passant


Here is a really simple system that creates 0 -10 folders recursively for x levels. Resulting in a structure listed in the picture. The concept is pretty simple, the method calls itself passing in the path and depth parameters. Where the path is the root path the folders should be created at that recursion level and the depth is the remaining sub-folders to to create. You will notice on each recursive call the depth parameter is reduced by one until it equals zero. At zero the recursion stops.

static void Main(string[] args)
{
    int maxDepth = 5;
    string initialPath = @"D:\testFolders";
    createFolders(initialPath, maxDepth);
}

static void createFolders(string path, int depth)
{
    depth--;
    for (int i = 0; i <= 10; i++)
    {
        string directory = Path.Combine(path, i.ToString());
        if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);
        if (depth > 0)
            createFolders(directory, depth);
    }
}

enter image description here

like image 35
Nico Avatar answered Oct 03 '22 22:10

Nico