Create a directory and intermediate directories in C#

[create directories]

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, 
        MessageBox.Show("Directory created.",
            "Directory Created", MessageBoxButtons.OK,

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 Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in directories and tagged , , , , , , , , , . Bookmark the permalink.

1 Response to Create a directory and intermediate directories in C#

  1. slearl says:

    Any chance you could do a tutorial on isolated storage?

Comments are closed.