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

376 views Asked by At
public IActionResult Upsert(ProductVM productVM,IFormFile? file)
{

    if (ModelState.IsValid) 
    {
        string wwwwRootPath = _webHostEnvironment.WebRootPath;
        if(file!=null)
        {
            string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            string productPath = Path.Combine(wwwwRootPath,@"Images\Product");
            var filePath = Path.Combine(fileName, productPath);
            using (var fileStream = new FileStream(filePath, FileMode.Create ))
            {
                file.CopyTo(fileStream);
            }
            productVM.Product.ImageUrl = @"\Images\Product\" + fileName;
        }
        _uniOfWork.Product.Add(productVM.Product);
        _uniOfWork.Save();
        TempData["success"] = "Category created successfully";
        return RedirectToAction("Index");
    }
    else
    {
        productVM.CategoryList = _uniOfWork.Category
        .GetAll()
        .Select(u => new SelectListItem
        {
            Text = u.Name,
            Value = u.Id.ToString(),
        });
    }

    return View(productVM);
}

I am trying to save a file inside wwwroot-> images folder but i am getting this exception "System.UnauthorizedAccessException: 'Access to the path '**\wwwroot\Images\Product' is denied.' " on my windows 11 machine i tried giving all the required permissions to the folder but still getting it cant make out what must i have missed

1

There are 1 answers

0
Yat Fei Leong On
  1. Go to server folder
  2. Right click and Select Properties
  3. Go to Security Tab
  4. Press Edit
  5. Click Add
  6. Type IIS_IUSRS and click Check Names
  7. Add Add the user

Also read the following for file upload security consideration https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-8.0