Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
directory

How to create a directory in C#

Aaron Xie

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.

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.

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring