3

I want to make multiple sub folders in a folder at once. Multiple Folders

Like in image i want to create A->B->C and D inside B all at once without loop. Is there any way to achieve it in C#

Pankaj Bhatia
  • 202
  • 1
  • 11

3 Answers3

2

Directory.CreateDirectory will create all directories in the given path, including any subdirectories.

using System.IO;

var paths = new [] { "F:\\A\\B\\C", "F:\\A\\B\\D" };

foreach (var path in paths) {
    try {
        // Determine whether the directory exists.
        if (Directory.Exists(path)) {
            Console.WriteLine($"Skipping path '{path}' because it exists already.");
            continue;
        }

        // Try to create the directory.
        var di = Directory.CreateDirectory(path);
        Console.WriteLine($"Created path '{path}' successfully at {Directory.GetCreationTime(path)}.");
    }
    catch (Exception e) {
        Console.WriteLine($"The process failed: {e}");
    }
}
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
  • Thanks @Georg but i was asking for a solution without any loop. I don't want run any loop. I had tried but not find any way without loop then i posted a question here. – Pankaj Bhatia Mar 01 '18 at 11:09
  • I do not think solving this without a loop is possible because you want to create two paths and there is no overload of `CreateDirectory` that takes more than one path as parameter. – Georg Patscheider Mar 01 '18 at 11:40
0

Try This code.

 private string GetUploadFileFolderPath()
    {

        string struploadUserImageFolderPath ="~/A/";
        string strGetStockUploadFolderName ="C";
        string strfullFolderPath = "~/A/" + "B" + "/" + strGetStockUploadFolderName + "/";
        return strfullFolderPath;

    }

 struploadUserImageFolderPath = GetUploadFileFolderPath();    // file path
                    if (!Directory.Exists(Server.MapPath(struploadUserImageFolderPath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(struploadUserImageFolderPath));
                    }
ravi polara
  • 564
  • 3
  • 14
0

var path = @"PATH_TO_FILE"; new FileInfo(path).Directory.Create();

Gal Levy
  • 39
  • 3