Create a directory 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 error.

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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.