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