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;
}
I get this error:
System.UnauthorizedAccessException: Access to the path 'F:\Documents HDD\spec-backend\Resources' is denied
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.
You may see “Access to the path is denied” error if the application is not able access to a path that is trying to read or write. This will show up as 401 Unauthorized error in IIS logs.
An UnauthorizedAccessException exception is typically thrown by a method that wraps a Windows API call. To find the reasons for the exception, examine the text of the exception object's Message property. UnauthorizedAccessException uses the HRESULT COR_E_UNAUTHORIZEDACCESS , which has the value 0x80070005.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With