Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core Access to the Path is Denied with IFormFile

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.

like image 829
user1994100 Avatar asked Jul 08 '17 06:07

user1994100


People also ask

Why is access to the path denied?

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.

What is UnauthorizedAccessException C#?

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.


1 Answers

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);
}
like image 192
user1994100 Avatar answered Sep 26 '22 03:09

user1994100