Trusted answers to developer questions

How to create a directory in C#

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Before we can create a directory, you must first import the System.IO namespace in C#. The namespace is a library that allows you to access static methods for creating, copying, moving, and deleting directories.

Creating the directory

You can use the Directory.CreateDirectory method to create a directory in the desired path. Take a look at the example below.

Press + to interact
string dir = @"C:\test";
// If directory does not exist, create it
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}

In the code above, use Directory.Exists to check whether the directory path exists. If it does not, you can use Directory.CreateDirectory to create the directory.

You can also create sub-directories, as seen below.

Press + to interact
string dir = @"C:\test\Aaron";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}

To create a sub-directory, you simply have to specify its path.

RELATED TAGS

c#
directory

CONTRIBUTOR

Aaron Xie
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?