ASP.Net Core 对路径的访问被 IFormFile 拒绝 [英] ASP.Net Core Access to the Path is Denied with IFormFile

查看:25
本文介绍了ASP.Net Core 对路径的访问被 IFormFile 拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Just writing a simple ASP.NET Core WebAPI and when using a simple POST endpoint accepting IFormFiles:

        [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 HDDspec-backendResources' 被拒绝

System.UnauthorizedAccessException: Access to the path 'F:Documents HDDspec-backendResources' is denied

我已经研究过它,显然它与我的目录为只读有关,但我无法弄清楚如何更改它,即使这样,我的 ASP.NET 控制器仍然会创建该目录.

I have looked into it and apparently it has something to do with my directory being readonly but I cannot figure out how to change this and even then the directory is being created by my ASP.NET controller anyway.

推荐答案

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

The answer in the end was that the FileStream object required the name of the file in the path, not just the directory.

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

这篇关于ASP.Net Core 对路径的访问被 IFormFile 拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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