user1994100
user1994100

Reputation: 601

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.

Upvotes: 8

Views: 13654

Answers (1)

user1994100
user1994100

Reputation: 601

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

Upvotes: 25

Related Questions