Johan Knape
Johan Knape

Reputation: 115

UnauthorizedAccessException when saving file, but can create a directory

I'm trying to save a file to the disk but I get UnauthorizedAccessException. The error says I have to get the right permissions on the folder, and I've tried every possible user I can find but it doesn't work.

Tried the following users

And given the full rights without it working.

What I find really strange is that I create a directory before I try to save the file and that works perfectly, it's when trying to save a file to that new directory that I get the UnautorhizedAccessException.

The code is the following:

    [HttpPost]
    public ActionResult Images(HttpPostedFileBase file, string boatId)
    {
        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/Images/" + boatId));
            Directory.CreateDirectory(path);
            file.SaveAs(path);

        }
        return View($"Filen på {boatId} har laddats upp");
    }

Any ideas at what I'm missing?

Upvotes: 2

Views: 2008

Answers (1)

Johan Knape
Johan Knape

Reputation: 115

Turns out what I was trying to do was saving the folder and not the file, I forgot to combine the fileName with the path.

Changed the Save part to the following:

file.SaveAs(Path.Combine(path, fileName));

Which solved the whole thing for me.

Upvotes: 5

Related Questions