ledgeJumper ledgeJumper - 3 years ago 445
ASP.NET (C#) Question

Could not find a part of the path C# asp.net, path is there


I have this code:

public ActionResult UploadCV(string userId, HttpPostedFileBase cvfile)
if (cvfile != null && cvfile.ContentLength > 0)
var bareFilename = Path.GetFileNameWithoutExtension(cvfile.FileName);
var fileExt = Path.GetExtension(cvfile.FileName);
//save to dir first
var path = Path.Combine(Server.MapPath("/App_Data/userfiles/"),
userId + "/");
var dir = Directory.CreateDirectory(path);
//save to db..
var user = Ctx.Users.FirstOrDefault(x => x.Id == userId);
user.CvLocation = "/App_Data/userfiles/" + userId + "/" + bareFilename + fileExt;
user.CvUploadDate = DateTime.Now;

return RedirectToAction("Index", "Settings", new { area = "" });

on the line:


I get the error

Could not find a part of the path

If I navigate to the path in explorer, it comes up fine.

What I am trying to solve is sort the user uploads by their unique GUID they have in the db. I wants the folder 'userfiles' to have a folder name of the users guid, and in that folder I have 'mycoolpic.png'

Any idea what I am doing wrong here?

Answer Source

You are trying to save without giving a filename. HttpPostedFileBase.SaveAs requires a parameter representing the filename not just the path. Simply use the server path combined with the bareFilename extracted just before.

 var path = Path.Combine(Server.MapPath, "/App_Data/userfiles/"),userId);
 var dir = Directory.CreateDirectory(path);
 cvfile.SaveAs(Path.Combine(path, bareFilename);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download