Languages
[Edit]
EN

C# / .NET - create directory with subdirectory

0 points
Created by:
Theodora-Battle
528

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

Quick solution:

string path = @"C:\path\directory\subdirectory1\subdirectory2"

if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}
directory/
  |
  +-- subirectory1/
          |
          +-- subdirectory2/

 

Practical example

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

using System;
using System.IO;

public static class Program
{
    public static void Main(string[] args)
    {
        string path = @"C:\path\directory\subdirectory1\subdirectory2";

        try
        {
            // Check if the directory exists
            if (Directory.Exists(path))
            {
                Console.WriteLine("That path already exists.");
                return;
            }

            // Create directory
            DirectoryInfo dir = Directory.CreateDirectory(path);
            Console.WriteLine("The directory was created successfully.");
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

Result:

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

References

  1. Directory.CreateDirectory Method (System.IO) | Microsoft Docs
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