Mauro Vinicius
Mauro Vinicius

Reputation: 1358

System.UnauthorizedAccessException: Access to the path '...' is denied

So, I'm kinda new to .NET core and I'm having a problem to copy a IFormFile to a folder in my project. I've been trying to see other questions about it but none of the answers had helped me. That's my code:

public async Task<string> AddImage(IFormFile image, int id)
{
    if (image.Length > 0)
    {
        var filePath = Path.Combine("images", ("apartamento" + id.ToString()), image.FileName);

        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await image.CopyToAsync(fileStream);
        }

        return filePath;
    }
} 

The problem is that it seems that I don't have permission (tried hard to see if everything is authorized) or something about my code it's not right.

I just wanna do a simple thing: receive an image in my API and save it so I can use in my project later. I have done it before but I'm facing some issues with .NET core.

If someone have other idea to do it, I'll be thankful. I'm thinking about saving the image as Base64 in my database but I'm not sure about which is the best option. Or the easiest.

Upvotes: 0

Views: 4361

Answers (1)

Anil Goel
Anil Goel

Reputation: 271

Try this

public async Task<string> AddImage(IFormFile image, int id)
{
    if (image.Length > 0)
    {
        var dir = Path.Combine("images", ("apartamento" + id.ToString()));
        var filePath = Path.Combine(dir, image.FileName);

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await image.CopyToAsync(fileStream);
        }

        return filePath;
    }
} 

Upvotes: 2

Related Questions