- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a folder if it does not exist in C#?
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.
Advertisements