【问题标题】:ASP.Net Core Access to the Path is Denied with IFormFileASP.Net Core 对路径的访问被 IFormFile 拒绝
【发布时间】:2017-12-12 11:58:36
【问题描述】:

只需编写一个简单的 ASP.NET Core WebAPI 并在使用接受 IFormFiles 的简单 POST 端点时:

        [HttpPost]
        public async Task<List<string>> Post(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);
            List<string> result = new List<string>();

            Console.WriteLine(files.Count);

            foreach (var f in files)
            {
                if (f.Length > 0)
                {
                    Directory.CreateDirectory("Resources");
                    using (var stream = new FileStream("Resources", FileMode.Create))
                    {
                        await f.CopyToAsync(stream);
                        result.Add(f.FileName);
                    }
                }
            }
            return result;
        }

我收到此错误:

System.UnauthorizedAccessException:访问路径 'F:\Documents HDD\spec-backend\Resources' 被拒绝

我已经调查过了,显然它与我的目录是只读的有关,但我不知道如何更改它,即使这样,我的 ASP.NET 控制器仍然在创建目录。

【问题讨论】:

  • 哪一行抛出异常?
  • 在文件流被实例化的那一行

标签: c# asp.net .net asp.net-web-api .net-core


【解决方案1】:

最后的答案是 FileStream 对象需要路径中的文件名,而不仅仅是目录。

using (var stream = new FileStream(Path.Combine("Resources", f.FileName), FileMode.Create))
{
    await f.CopyToAsync(stream);
    result.Add(f.FileName);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    相关资源
    最近更新 更多