[RESOLVED]Server.MapPath check for folder and create

I’m uploading an image to a folder images. it’s working fine.but what I actually want is to look for a folder name (I have the folder name) if not found create that folder and give it that name.how could that happen?

this is what I have done so far:

string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);

instead of images I should have folderName.

bool exists = System.IO.Directory.Exists(Server.MapPath(" YOUR PATH "));

if(!exists)
    System.IO.Directory.CreateDirectory(Server.MapPath(
" YOUR PATH "
));

Please try as this to check if the directory exists if not create.

Post back your queries if any.

Thanks :)

this is my upload function.please do edit:

public ActionResult FileUpload(HttpPostedFileBase file)
{

if (file != null)
{

string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);

// save image in folder
file.SaveAs(physicalPath);

//save new record in database
datum newRecord = new datum();
newRecord.category = Request.Form["category"];
newRecord.description = Request.Form["description"];
newRecord.imagePath = ImageName;
db.data.Add(newRecord);
db.SaveChanges();

}
//Display records
return RedirectToAction("Display");
}

public ActionResult FileUpload(HttpPostedFileBase file)
{

if (file != null)
{

string ImageName = System.IO.Path.GetFileName(file.FileName);
string dirPath = Server.MapPath("~/images/");
if(!System.IO.Directory.Exists(dirPath))
{
System.IO.Directory.CreateDirectory(dirPath);
}
string physicalPath = Server.MapPath("~/images/" + ImageName);

// save image in folder
file.SaveAs(physicalPath);

//save new record in database
datum newRecord = new datum();
newRecord.category = Request.Form["category"];
newRecord.description = Request.Form["description"];
newRecord.imagePath = ImageName;
db.data.Add(newRecord);
db.SaveChanges();

}
//Display records
return RedirectToAction("Display");
}

Leave a Reply