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.
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.
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.
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!