Home  >  Article  >  Backend Development  >  How to create a folder in C# if it does not exist?

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

WBOY
WBOYforward
2023-09-11 11:57:091838browse

In order to create the directory, we must first import the System.IO namespace in C#. A 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 a directory exists before performing any file operations in C# as the compiler will throw an 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.

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

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 subfolders in the D: directory.

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

The above is the detailed content of How to create a folder in C# if it does not exist?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete