UPDATE - the answer to my question was not actually a true permission issue.
I ended up solving my problem when I realized I was actually trying to save my file incorrectly. My section of code httpPostedFile.SaveAs(fileSavePath)
is wrong.
What that ends up doing is trying to save a file to that path which has the exact
same name as the path as well. To fix this I just appended the file name onto fileSavePath
and then the file was saved successfully.
So now that section of code looks like this:
var extension = Path.GetExtension(httpPostedFile.FileName).toLower();
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png")
{
var fileName = Path.GetRandomFileName() + extension;
var fileSavePath = serverPath + path + fileName;
httpPostedFile.SaveAs(fileSavePath);
}
P.S. - if you could vote to get this question reopened so that I can provide this answer that would be appreciated, since the post this is supposedly a duplicate of didn't actually end up solving my problem.
ORIGINAL POST
What I'm trying to do is fairly simple but I'm getting hung up on this exception:
An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code
Additional information: Access to the path 'C:\Users\TCT-User-2\Source\Repos\Shift_Production\Shift.Web\Content\images\UserAvatars' is denied.
I've looked at some other similar problems here on SO and they all suggest checking to make sure the folder or files aren't read only. As far I can tell they're not but I'm still getting this issue. So maybe it's something else I'm doing wrong in my code?
I'm basically just uploading an image to my Web API
project and then trying to save it locally to the server.
Here is what I have to do that:
[Route("Account/Avatar")]
[HttpPost]
public IHttpActionResult UploadAvatar()
{
string serverPath = _appSettingService.GetApplicationSettings().ServerPath;
string imagePath = _appSettingService.GetApplicationSettings().AppUserProfileImagePath;
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
var httpPostedFile = HttpContext.Current.Request.Files["file"];
if (httpPostedFile != null)
{
var fileSavePath = serverPath + imagePath;
httpPostedFile.SaveAs(fileSavePath);
}
}
return Ok();
}