Create Folder if No Exists in C#

 

                     Create Folder if No Exists using C#


When we upload file in specific folder first we have to create folder in project.
If the folder does not exist, we want to first create it, and then save the file to the folder. If the folder already exists, then just save the file in it.

I want to create a folder named  "Projectfiles" in my project. Below i have mapped the path of folder 

using System.Web;

string Projectfiles = HttpContext.Current.Server.MapPath("~/Projectfiles/");

Then we have to check if this folder is exists 

using System.IO

   if (!Directory.Exists(Projectfiles))
  {
                
  }

Import using System.IO  for Directory and  the Directory this will check whether the folder exists in our project or not 

If we want to created Sub folder in side folder we will write like below 

string Projectfiles = HttpContext.Current.Server.MapPath(@"~/Files/Projectfiles/");

I the Projectfiles it will map with the Projectfiles folder inside File folder then
 we will check again if it exists in our project or not.
 
 

To create the directory of the folder we will have to write code inside if condition
 as below.

Directory.CreateDirectory(Projectfiles );

Final Code to create folder is written below 


using System.IO; using System.Net; using System.Net.Http; using System.Web;

string ProjectLoafiles = HttpContext.Current.Server.MapPath("~/Projectfiles/");
if (!Directory.Exists(ProjectLoafiles))
{
    Directory.CreateDirectory(ProjectLoafiles);
}