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