Creating A Directory by C# Code

In this post, we will demonstrate an example of creating a directory by using C# code.

For creating a directory in file system, you need to import System.IO namespace in program and CreateDirectory() method of the Directory class will help you to create folder. CreateDirectory() requires a parameter that is the path of directory.

We are giving below the complete example C# code of creating directory on the specified path.

using System;
using System.IO;

class DirectoryExample
{      
public static void Main()
{
    string dirPath = "D:\\Example Folder";
  try
  {
    Directory.CreateDirectory(dirPath);      
    Console.WriteLine("Directory has been created successfully");
  }
  catch (Exception ex)
  {
    Console.WriteLine(ex.Message);
  }
}
}

When you run the above code, you will see that a directory with name “Example Folder” has been created in D drive.

Leave a Reply