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?
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.
Let's create the required path as a string
:
string dir = Path.Combine(folderBrs.SelectedPath + textBox1.Text.Trim(),
"subfolder1",
"subfolder2");
Then we can create the directory:
Directory.CreateDirectory(dir);
Sure, you can combine both fragments into one:
using System.IO;
...
using (FolderBrowserDialog folderBrs = new FolderBrowserDialog()) {
if (folderBrs.ShowDialog() == DialogResult.OK)
Directory.CreateDirectory(Path.Combine(
folderBrs.SelectedPath + textBox1.Text.Trim(),
"subfolder1",
"subfolfer2"
));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.