UnauthorizedAccessException when saving file, but can create a directory

吃可爱长大的小学妹 提交于 2020-01-30 09:23:10

问题


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:

    [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?


回答1:


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.



来源:https://stackoverflow.com/questions/44949026/unauthorizedaccessexception-when-saving-file-but-can-create-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!