I have a profile page where the user can change their profile picture, When the user clicks submit their old profile picture is delete and replace with a the new one. However, when I try and delete the image it gives the error below:
IOException: The process cannot access the file 'C:\Users\Shayan\source\repos\RestaurantWeb\RestaurantWeb\wwwroot\Images\Users\92487709-5b2f-417c-a64f-4661962693cf_imb5ohqzqr511.jpg' because it is being used by another process.
Here is my snippet of code where I add and delete the images:
if (accountDetailsViewModel.ProfilePicture != null)
{
string fileName = FileUploadHelper.GetUniqueFileName(accountDetailsViewModel.ProfilePicture.FileName);
string filePath = FileUploadHelper.GetProfileFilePath(fileName, _webHostEnvironment);
await accountDetailsViewModel.ProfilePicture.CopyToAsync(new FileStream(filePath, FileMode.Create));
user.ProfileImagePath = fileName;
string previousImageFilePath = FileUploadHelper.GetProfileFilePath(accountDetailsViewModel.PreviousPicturePath, _webHostEnvironment);
if (System.IO.File.Exists(previousImageFilePath) && accountDetailsViewModel.PreviousPicturePath != "noprofilepic.jpeg")
{
System.IO.File.Delete(previousImageFilePath);
}
}
Why is this happening? Am I meant to be closing the file? I'm not using File.Create()
so I can't really close it like:
var img = File.Create(filePath);
img.Close();