保存文件时出现UnauthorizedAccessException,但可以创建目录 [英] UnauthorizedAccessException when saving file, but can create a directory

查看:93
本文介绍了保存文件时出现UnauthorizedAccessException,但可以创建目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件保存到磁盘,但出现UnauthorizedAccessException. 该错误表明我必须获得该文件夹的正确权限,并且我已经尝试了所有可能找到的用户,但是它不起作用.

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.

尝试了以下用户

  • 网络
  • 网络服务
  • IUSR
  • IUSR_ [计算机名]

并赋予了其全部权利,而它却无法正常工作.

And given the full rights without it working.

我真正感到奇怪的是,我在尝试保存文件之前创建了一个目录,并且效果很好,这是在尝试将文件保存到新目录时,我得到了UnautorhizedAccessException.

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.

代码如下:

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

推荐答案

结果是我要保存的是文件夹而不是文件,我忘记了将fileName与路径结合起来.

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.

这篇关于保存文件时出现UnauthorizedAccessException,但可以创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆