Search code examples
c#directorysubdirectoryfolderbrowserdialog

How to create a folder having some subfolders, in a root folder selected by the user?


i have this code to create subfolders in the path the user choose

FolderBrowserDialog folderBrs = new FolderBrowserDialog();

        if (folderBrs.ShowDialog() == DialogResult.OK)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(folderBrs.SelectedPath;

            dir.CreateSubdirectory("subfolder1");
            dir.CreateSubdirectory("subfolder2");

        } 

it works fine, but the problem is ir makes the subfolders without the principal folder, so y tried this code

FolderBrowserDialog folderBrs = new FolderBrowserDialog();

        if (folderBrs.ShowDialog() == DialogResult.OK)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(folderBrs.SelectedPath + textBox1.Text.Trim());

            dir.CreateSubdirectory("subfolder1");
            dir.CreateSubdirectory("subfolder2");

        } 

as you can see, the only diference is the textBox addition, but when i type the name it doesn't create the folder, it doesn't anything, but the curios thing is, if i choose an existent folder it creates the folder with the subfolders, but the name of the principal folder is mixed with the name of the existent folder that i choosed

what i am doing wrong? any suggestion?


Solution

  • Here is the code corrected, assuming the selected path exists:

    if ( folderBrs.ShowDialog() == DialogResult.OK )
    {
      var dir = new DirectoryInfo(folderBrs.SelectedPath);
      dir = dir.CreateSubdirectory(textBox1.Text.Trim());
      dir.CreateSubdirectory("subfolder1");
      dir.CreateSubdirectory("subfolder2");
    }
    

    We take an instance of a directory info for the selected path.

    Next we create the subfolder from the textbox.

    Then we create the two subfolders in it.