ledgeJumper
ledgeJumper

Reputation: 3630

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

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?

Upvotes: 2

Views: 21776

Answers (3)

Kondwani Hara
Kondwani Hara

Reputation: 11

In my case, I am sharing the source code with two colleagues through Git and the file uploads directory though present within my colleagues' Visual Studio upon pull, was not present in File Explorer. So I had to create a txt file, add it to Git, and then push it to the remote repository. When my friends pulled, they had the folder present in Visual Studio as well as File Explorer. This resolved the problem.

Upvotes: 0

tno2007
tno2007

Reputation: 2168

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");

Upvotes: 1

Steve
Steve

Reputation: 216363

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

Upvotes: 3

Related Questions