Create a Folder in C#

In this article, we will introduce methods to create a new folder in a specified directory.

  • Use the CreateDirectory() method

Use the CreateDirectory() Method to Create a Folder in C

We will use the system-defined method CreateDirectory() to create a new folder in a specified directory. If the folder already exists, then it does not take any action. The correct syntax to use this function is as follows.

System.IO.Directory.CreateDirectory(string path);

The built-in method CreateDirectory() has only one parameter. The detail of its parameter is as follows.

Parameters Description
path mandatory It is the string containing the path information where we want to create a new folder.

This method returns a DirectoryInfo object, which shows the directory at the specified path.

The program below shows how we can use the CreateDirectory() method to create a new folder.

using System;
using System.IO;


class CreateFolder
{
    static void Main()
    {
        string folderPath = @"D:\MyFolder";
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
            Console.WriteLine(folderPath); 
        }
    }
}

We have created a folder named MyFolder in local disk D. We have passed the folder path. The method will create the folder if it does not exist.

Output:

D:\MyFolder
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Directory

  • Delete All Files in a Directory in C#