rooted path error

I’m having a rooted path error on the save as what is the problem.although when breakpoint on the physical path.it is giving me the correct path.

string category = Request.Form["category"];

if (file != null)
{

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

bool exists = System.IO.Directory.Exists(Server.MapPath(physicalPath));

if (!exists) {
System.IO.Directory.CreateDirectory(Server.MapPath(physicalPath));
}

// 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();

You are actually checking the file path in directory case, check only for directory that it is there or not, if not create directory.

  Do it like this:

string ImageName = System.IO.Path.GetFileName(file.FileName);
string directoryPath = "~/category/";       // directory path
string filePath = directoryPath + ImageName; // file physical path



if (!System.IO.Directory.Exists(Server.MapPath(directoryPath)) {    // check if directory not exists
System.IO.Directory.CreateDirectory(Server.MapPath(directoryPath)); // create directory
}

// save image in folder
file.SaveAs(filePath); // save file in that path

You are here checking Directory.Exists on file path. Where as you have to check on directory path only. So check if Directory.Exists on the path without imagename and after that save image on your physical path with image name.

sorry but still same error

Please post your updated code here.

I tried both codes and both still give the same error of rooted path

Leave a Reply