Home > Backend Development > C#.Net Tutorial > 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
Release: 2023-09-11 11:57:09
forward
1915 people have browsed it

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();
      }
   }
}
Copy after login

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();
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template