Skip to content
Related Articles

Related Articles

C# Program to Create a Directory

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Nov, 2021
View Discussion
Improve Article
Save Article

A directory is a file system that stores file. Now our task is to create a directory in C#. We can create a directory by using the CreateDirectory() method of the Directory class. This method is used to create directories and subdirectories in a specified path. If the specified directory exists or the given path is invalid then this method will not create a directory. To use CreateDirectory() method we have to import the system.IO namespace in the program.

Syntax:

public static System.IO.DirectoryInfo CreateDirectory (string path);

Parameter: path is the directory path.

Return: This will return the object of the specified created directory.

Exception: It will throw the following exception:

  • IOException: This exception occurs when the directory specified by path is a file.
  • UnauthorizedAccessException: This exception occurs when the caller does not have the required permission.
  • ArgumentException: This exception occurs when the path is prefixed with, or contains, only a colon character (:).
  • ArgumentNullException: This exception occurs when the path is null.
  • PathTooLongException: This exception occurs when the specified path, file name, or both exceed the system-defined maximum length.
  • DirectoryNotFoundException: This exception occurs when the specified path is invalid 
  • NotSupportedException: This exception occurs when the path contains a colon character(:) that is not part of a drive label (“D:\”).

Example:

C#




// C# program to illustrate how
// to create directory
using System;
using System.IO;
  
class GFG{
      
public static void Main()
{
      
    // Create directory named Sravan in C drive
    // Using CreateDirectory() method
    Directory.CreateDirectory("C:\\sravan");
      
    Console.WriteLine("Created");
}
}


Output:

Created

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!