EN
C# / .NET - create directory with subdirectory
0 points
In this article, we would like to show you how to create directory in C#.
Quick solution:
xxxxxxxxxx
1
string path = @"C:\path\directory\subdirectory1\subdirectory2"
2
3
if (!Directory.Exists(path))
4
{
5
Directory.CreateDirectory(path);
6
}
xxxxxxxxxx
1
directory/
2
|
3
+-- subirectory1/
4
|
5
+-- subdirectory2/
In this example, we use CreateDirectory()
method to create directory with subdirectories if it doesn't exist.
xxxxxxxxxx
1
using System;
2
using System.IO;
3
4
public static class Program
5
{
6
public static void Main(string[] args)
7
{
8
string path = @"C:\path\directory\subdirectory1\subdirectory2";
9
10
try
11
{
12
// Check if the directory exists
13
if (Directory.Exists(path))
14
{
15
Console.WriteLine("That path already exists.");
16
return;
17
}
18
19
// Create directory
20
DirectoryInfo dir = Directory.CreateDirectory(path);
21
Console.WriteLine("The directory was created successfully.");
22
}
23
catch (Exception e)
24
{
25
Console.WriteLine("The process failed: {0}", e.ToString());
26
}
27
}
28
}
Result:
