Directory.CreateDirectory
This C# method from System.IO
creates a new folder. It allows us to easily create new directories. It is a static
method.
CreateDirectory
As with all calls to file or directory-handing methods, it can throw exceptions. These should be handled.
First, Directory.CreateDirectory
is available in the System.IO
namespace. You can either add the using directive at the top of your file, or use the fully qualified name.
CreateDirectory
method group, but this example only shows the one with one parameter.string
literals.using System.IO; class Program { static void Main() { // // Create new folder in C:\ volume. // Directory.CreateDirectory("C:\\newfolder"); // // Create another directory with different syntax. // Directory.CreateDirectory(@"C:\newfolder2"); // // Create an already-existing directory (does nothing). // Directory.CreateDirectory(@"C:\newfolder2"); } }There are 2 folders on your C:\ drive: 1. newfolder 2. newfolder2
When interfacing with the file system, you should always prepare for exceptions and provide code for recovering from them. CreateDirectory()
throws 7 types of exceptions.
To clear an entire directory if it exists, you can call Directory.Exists
, and then Directory.GetFiles
, and finally File.Delete
on each path.
We tested a program and discussed issues related to Directory.CreateDirectory
. We provided hints on specifying folder paths and on further uses of CreateDirectory
.