Johan Knape Johan Knape - 2 months ago 11
C# Question

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

  • Network

  • Network Services

  • IUSR

  • IUSR_[Computername]

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:

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

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

Any ideas at what I'm missing?

Answer Source

Turns out what I was trying to do was saving the folder and not the file, I forgot to compine 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.