Languages
[Edit]
EN

C# / .NET - create directory

3 points
Created by:
Marcino
720

In this article, we would like to show you how to create directory in C#.

Quick solution:

string path = @"C:\path\to\directory";

if (!Directory.Exists(path))
    Directory.CreateDirectory(path);

Warning: the above source code may thrown some exceptions, so it is good to catch or forward them.

 

Practical example

In this example, we use Directory.CreateDirectory() method to create directory if it doesn't exist yet.

using System;
using System.IO;

public static class Program
{
    public static void Main(string[] args)
    {
        string path = @"C:\Users\Username\Desktop\example\dir1";

        try
        {   
            if (Directory.Exists(path)) // checks if the directory exists
                Console.WriteLine("That directory already exists.");
            
            else
            {
                DirectoryInfo directory= Directory.CreateDirectory(path); // creates a directory

                Console.WriteLine("The directory was created successfully.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The operation failed: {0}", e.ToString());
        }
    }
}

Result:

C# / .NET - create directory
C# / .NET - create directory

References

  1. Directory.CreateDirectory Method (System.IO) | Microsoft Docs

Alternative titles

  1. C# / .NET - create folder
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join