Summary: in this tutorial, you’ll learn how to create a directory in C# using the
static method.Directory.CreateDirectory
()
Introduction to the C# Directory.CreateDirectory() static method
The
static method allows you to create a new directory. Here’s the syntax of the Directory.CreateDirectory
()Directory.CreateDirectory()
method:
public static DirectoryInfo CreateDirectory (
string path
);
Code language: C# (cs)
In this syntax, the path
specifies the directory to create.
The CreateDirectory()
static method creates a new directory and returns a DirectoryInfo
object that represents the directory of the specified path
.
If the path to the directory exists, the CreateDirectory()
doesn’t throw an exception. Also, it returns a DirectoryInfo
object that represents the existing directory.
The CreateDirectory()
static method raises an IOException
if the path
is a file, not a directory.
If the path
contains subdirectories that do not exist, the CreateDirectory()
static method also creates corresponding subdirectories.
For example, if you want to create a directory like C:\backup\2023\03\
and the C:\backup
already exists, the CreateDirectory()
static method will create two directories:
C:\backup\2023
C:\backup\2023\03
The
method also allows you to create a directory on a remote computer to which the program has access. For example, you can create a directory to a shared folder like CreateDirectory()
@"\\shared\reports\sales\"
.
Using C# Directory.CreateDirectory() method to create new directories example
The following program demonstrates how to use the
method to create a directory Directory.CreateDirectory()
2023
in the C:\backup
directory and 12 subdirectories (from 00
to 12
) inside the directory 2023
:
using static System.Console;
string dirname = @"C:\backup\2023";
for (int i = 1; i <= 12; i++)
{
Directory.CreateDirectory(
Path.Combine(dirname, i.ToString("00"))
);
}
Code language: C# (cs)
How it works.
First, declare a dirname
variable that stores the parent directory:
string dirname = @"C:\backup\2023";
Code language: C# (cs)
Second, iterate over the number from 1 to 12 and create the subdirectories from 00
to 12
:
for (int i = 1; i <= 12; i++)
{
Directory.CreateDirectory(
Path.Combine(dirname, i.ToString("00"))
);
}
Code language: C# (cs)
Note that we use the i.ToString("00")
to pad a leading zero to a number like 01
, 02
, etc.
The program will create the directories structure like this:
c:\backup
└── 2023
├── 01
├── 02
├── 03
├── 04
├── 05
├── 06
├── 07
├── 08
├── 09
├── 10
├── 11
└── 12
directory: 13
Code language: plaintext (plaintext)
Summary
- Use the
method to create a new directory if it does not exist.Directory.CreateDirectory()