How to create a folder if it does not exist in C#?

CsharpServer Side ProgrammingProgramming

For creating a directory, we must first import the System.IO namespace in C#. The namespace is a library that allows you to access static methods for creating, copying, moving, and deleting directories.

It is always recommended to check if the Directory exist before doing any file operation in C# because the complier will throw exception if the folder does not exist.

Example

using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string folderName = @"D:\Demo Folder";
         // If directory does not exist, create it
         if (!Directory.Exists(folderName)) {
            Directory.CreateDirectory(folderName);
         }
         Console.ReadLine();
      }
   }
}

The above code will create a Demo Folder in the D: directory.

Directory.CreateDirectory can also be used to create subfolders.

Example

using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         string folderName = @"D:\Demo Folder\Sub Folder";
         // If directory does not exist, create it
         if (!Directory.Exists(folderName)) {
            Directory.CreateDirectory(folderName);
         }
         Console.ReadLine();
      }
   }
}

The above code will create a Demo Folder with a Sub Folder in the D: directory.

raja
Published on 08-Aug-2020 08:52:19
Advertisements