Recursive Folder creation
.net, c#, recursion
Solution
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);
}
}
Problem
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