代码之家  ›  专栏  ›  技术社区  ›  Robin

如何创建包含项目中所有文件的文件夹?

  •  -1
  • Robin  · 技术社区  · 7 年前

    我正在中创建应用程序 C# Create Exit .

    如果按create,则输入项目名称 TextBox img js MsgBox ). 代码如下:

    //Unable to create project
            string mydir = Environment.SpecialFolder.MyDocuments + "\\" + textBox1.Text;
            if (Directory.Exists(mydir) == true)
            {
                    MessageBox.Show("The project name: " + textBox1.Text + " has already been created. Please consider renaming a different project name.", "Netplait", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    textBox1.Focus();
                    return;
            }
    
            if (Directory.Exists(mydir) == false)
            {
                Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), textBox1.Text));
            }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Steve    7 年前

    Environment.SpecialFolder.MyDocuments 是枚举,而不是现有目录的路径。代码失败,因为将此枚举值连接到文本框中的字符串没有意义。

    string mydir = Environment.GetFolderPath(Environement.SpecialFolder.MyDocuments);
    mydir = Path.Combine(myDir, textBox1.Text);
    if(DirectoryExists(myDir))
    {
        MessageBox.Show(.....);
        textBox1.Focus();
        return;
    }
    else
    {
        Directory.CreateDirectory(myDir);
    }
    

    还要注意,要组合字符串并生成有效路径,最好将此任务留给专门的方法 Path.Combine .
    顺便说一句,它就在目录中。CreateDirectory是代码的一部分。