Create Folder In .NET Core Using C#.Net

How to create or add sub folder or directory if not exists in parent in .net core using c#.net in console or windows application on given path.
In today's article I will show you how you can create a folder in .NET core using c#.net. This code example you can use in your windows application or in your console application to create a folder in a given path in .NET core using c#.net.

First let's decide a path where we will create the folder. Please check the path below there is no folder currently.

Empty folder in c#.net

Here we will use the console application using c#,net. Now for this article first we will create a new console application and add the below code.

string folderLocation = "D:\\DemoProject\\DemoFolder\\";
Console.WriteLine("----Create Folder In Path------");
Console.WriteLine("Enter Your Folder Name: ");
string? subfoldername = Console.ReadLine();
if (!string.IsNullOrEmpty(subfoldername))
{
    string creatrdFolderPath = string.Format("{0}{1}", folderLocation, subfoldername);
    if (!Path.Exists(creatrdFolderPath))
    {
        Directory.CreateDirectory(creatrdFolderPath);
        Console.WriteLine("Folder crated successfully");
    }
    else
    {
        Console.WriteLine("Folder alrady exists");
    }
}
Console.ReadLine();
In above code first I have declared a string type variable and assign a value as a local path in it. After that I have taken an input by the user. In this input user will provide the folder name which he wants to create. 
After that i have validated the user enter path is empty or not. If it is not empty. On that case it will combine the parent folder path and the user entered folder name. Please check the below code here I have used string.Format() to concatenate the string.
 string creatrdFolderPath = string.Format("{0}{1}", folderLocation, subfoldername);
Now let's check the code which is used to validate the folder already exists or not. If it already exists code display message that folder already exists. otherwise, it will move further to create the folder.
if (!Path.Exists(creatrdFolderPath))
After validating folder, code to create the folder have been written. Here Directory.CreateDirectory() is used to create the folder by passing the path.
Directory.CreateDirectory(creatrdFolderPath);
After creating the folder, a message has been displayed to user. Now let's run the code to check the output.

Create Folder In .NET Core Using C#.Net

Here we can see the folder is created successfully. Now lets check the parent folder path.

Create Folder In .NET Core Using C#.Net

Now let's
again run the code and enter the same sub folder name to create it.

Create Folder In .NET Core Using C#.Net
Create Folder In .NET Core Using C#.Net.zip 286KB

Post a Comment