How to create mutiple directories with sub-directories?

275 Views Asked by At

I have this stuation. I would like to create 12 subdirectories from the root, 30 subdirectories from each subdirectory at index 1 and 24 subdirectories from each subdirectory at index 2. I know that:

DirectoryInfo di = Directory.CreateDirectory(@"c:\Users\Public\Root");

creates one subdirectory everytime. How to do that in one shot? (just for example the first 30).

2

There are 2 best solutions below

6
On BEST ANSWER

It's hard to tell what you actually want, however this might point you in the right direction.

Declare your directories:

var rootDir = @"C:\SomeRoot";

var directoryList = new List<string>()
{
   "dir1",
   "dir2",
   "dir3"
};
var subDirectoryList = new List<string>()
{
   "subDir1",
   "subDir2",
   "subDir3"
};

Method

private void CreateDirectories(string root, List<String> directoryList, List<String> subDirectoryList)
{
   foreach (var dir in directoryList)
   {
      var currentDir = Path.Combine(root, dir);

      foreach (var subDir in subDirectoryList)
      {
         Directory.CreateDirectory(Path.Combine(currentDir, subDir));
      }

   }
}

Usage

CreateDirectories(rootDir,directoryList,subDirectoryList)

Output

C:\SomeRoot\dir1\subDir1
C:\SomeRoot\dir1\subDir2
C:\SomeRoot\dir1\subDir3
C:\SomeRoot\dir2\subDir1
C:\SomeRoot\dir2\subDir2
C:\SomeRoot\dir2\subDir3
0
On

There is no method to create multiple independent directories at once. However, note that the Directory.Create() method will create all of the directories named in the target path. E.g. if the C:\Users\Public\Root directory is empty, then calling Directory.Create(@"C:\Users\Public\Root\one\two\three"); will create the one, two, and three subdirectories required, all in that single call.

You can take advantage of that to create just the lowest-level directories you need, which would at least avoid the initial 12 subdirectory operations. You would still need to create the individual 30, 24, etc. subdirectories in individual calls.

(Your question is pretty vague about what you're actually trying to do so I can't say exactly what would happen beyond that, without more details).