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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.