Title: Create directories and intermediate directories in C#
The System.IO.Directory class's CreateDirectory method creates a directory. If the directory's path includes missing intermediate directories, it creates them, too. For example, if C:\DirA is empty and you use CreateDirectory to create C:\DirA\DirB\DirC, then the method automatically creates DirB as well as DirC.
Finally if you ask CreateDirectory to create a directory that already exists, the method returns without throwing an exception.
When you enter a directory path in this example's TextBox and click the Create button, the following code executes.
// Create the directory.
private void btnCreate_Click(object sender, EventArgs e)
{
if (Directory.Exists(txtDirectory.Text))
{
MessageBox.Show("This directory already exists.",
"Already Exists", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
Directory.CreateDirectory(txtDirectory.Text);
MessageBox.Show("Directory created.",
"Directory Created", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
The code uses the Directory class's Exists method to see if the directory already exists. If the directory exists, the code displays a message. If the directory does not exist, the code uses the CreateDirectory method to create it.
Download the example to experiment with it and to see additional details.
|