[英]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它工作正常,但问题是 ir 使子文件夹没有主文件夹,所以你尝试了这段代码
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
:
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"
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.