EN
C# / .NET - create directory
3
points
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:
