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.
Detail There are two overloads in the CreateDirectory method group, but this example only shows the one with one parameter.
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
Exceptions. 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.
Tip Depending on the purpose of your program, you can log these exceptions of terminate your program with an error message.
Clear. To clear an entire directory if it exists, you can call Directory.Exists, and then Directory.GetFiles, and finally File.Delete on each path.
Also We sometimes need to recursively walk through directories. A variety of methods can be used.
A summary. We tested a program and discussed issues related to Directory.CreateDirectory. We provided hints on specifying folder paths and on further uses of CreateDirectory.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.