Home
C#
Directory.CreateDirectory, Create New Folder
Updated Apr 8, 2022
Dot Net Perls
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.
Exceptions with CreateDirectory. As with all calls to file or directory-handing methods, it can throw exceptions. These should be handled.
IOException
Exception
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.
Overload
And You can open the C:\ folder on your computer to check the results. The directories should now exist.
Detail The first call uses the double-backslash syntax. A single backslash is the standard escape character in C-style string literals.
String Literal
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.
File List Recursive
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.
This page was last updated on Apr 8, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen