How to Create a Directory in C#

The Directory class is used to create a new directory in C#. Here is an C# example that shows how to create a folder.

The System.IO.Directory class in the .NET Framework class library provides static methods for creating, copying, moving, and deleting directories and subdirectories. Before you can use the Directory class, you must import the System.IO namespace. 

using System.IO;

Create a Directory 

The Directory.CreateDirectory method creates a directory with the specified Windows security in the specified path. You can also create a directory on a remote computer.

The following code snippet creates a Temp folder in C:\ drive if the directory does not exist already.

string root = @"C:\Temp";
string subdir = @"C:\Temp\Mahesh";
// If directory does not exist, create it. 
if (!Directory.Exists(root))
{
    Directory.CreateDirectory(root);
}

The CreateDirectory is also used to create a sub directory. All you have to do is to specify the path of the directory in which this subdirectory will be created. The following code snippet creates "Mahesh" subdirectory in the C:\Temp directory.

// Create a sub directory
if (!Directory.Exists(subdir))
{
    Directory.CreateDirectory(subdir);
}

Download free book: Working with Directories in C#

 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.