First let's decide a path where we will create the folder. Please check the path below there is no folder currently.
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.Here we can see the folder is created successfully. Now lets check the parent folder path.
Now let's
again run the code and enter the same sub folder name to create it.
again run the code and enter the same sub folder name to create it.