2

Lost.

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);
            cvfile.SaveAs(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;
            Ctx.SaveChanges();

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

on the line:

cvfile.SaveAs(path);

I get the error

Could not find a part of the path 
'C:\Users\me\big\ol\path\App_Data\userfiles\4cf86a2c-619b-402a-80db-cc1e13e5288f\'.

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?

ledgeJumper
  • 3,480
  • 14
  • 43
  • 91
  • 2
    Typically, this means there's a permissions issue. When teh runtime doesn't have permissions to access a resource, it can throw a not found exception. – David Feb 10 '14 at 20:58
  • 1
    If you save the image you need to add it's file-name: `Path.Combine(path, "mycoolpic.png")` instead of saving it as directory. – Tim Schmelter Feb 10 '14 at 20:58

2 Answers2

3

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);
Steve
  • 208,592
  • 21
  • 221
  • 278
1

I had this problem in the production environment, but not during development.

My problem was because I was omiting the ~ symbol.

I went from this:

var path = Server.MapPath("/App_Data/templates/registration.html");

to this:

var path = Server.MapPath("~/App_Data/templates/registration.html");
aaron
  • 30,879
  • 5
  • 34
  • 79
tno2007
  • 1,656
  • 22
  • 15