-1

I'm creating an application In C# that shows a dialog on startup and will ask for the project name. Meanwhile, there are 2 buttons I added: Create and Exit.

If you'd press create, the name of the project you'd type in the TextBox will be saved with that name in the Documents folder. Inside the project folder will be containing 2 separate folders called img and js. And if you tried the next time to create a project with a name that the folder exists, It will not overwrite the folder (let's just say i showed up a MsgBox). Here's the code:

//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));
        }
Robin
  • 127
  • 10
  • So you are asking about how to delete folder and create a new one or how to detect that folder already exists? – Aleks Andreev Jul 29 '17 at 15:29
  • Create a folder directory with the Textbox input name, then if we typed the same project name like we did before, it will detect and disable request – Robin Jul 29 '17 at 15:31
  • You need to call [Directory.Exists](https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx) method – Aleks Andreev Jul 29 '17 at 15:36
  • I tried doing that it did not work. Ill edit my post and add the code real quick – Robin Jul 29 '17 at 15:38
  • 1
    Why don't you already use `Path.Combine` when initializing `mydir`? – Ian H. Jul 29 '17 at 15:49

1 Answers1

3

Environment.SpecialFolder.MyDocuments is an enum, not a path to an existing directory. Your code fails because concatenating this enum value to the string in the textbox makes no sense.

Instead you get the actual MyDocument folder with

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);
}

Notice also that to combine string and make valid paths it is better to leave this task to the specialized method Path.Combine.
By the way, you have it right in the Directory.CreateDirectory part of your code.

Steve
  • 213,761
  • 22
  • 232
  • 286