[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Create directories and intermediate directories in C#

[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.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.