Home
Map
Directory.CreateDirectory, Create New FolderCreate new folders with the Directory.CreateDirectory method from System.IO.
C#
This page was last reviewed on Apr 8, 2022.
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 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.
This page was last updated on Apr 8, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.