I have an application that I am writing in WPF. It's pretty straightforward, I have this property of type string that reads the path of an image file (.png) and checks for it's resolution. If the dpi is not 96 then it sets the resolution to 96. Easy. Well I got that portion done, however, When I have to delete the old file and save it with the one with the correct resolution I get an error saying:
System.IO.IOException: 'The process cannot access the file 'C:\MyAwesomeProjects\Resources\Button_A.png' because it is being used by another process.'
This is what I am doing in my code. This is in my ViewModel
private string _bkImage = "";
public virtual string BkImage
{
get {return _bkImage ;}
set{
FileStream stream = new FileStream(value, FileMode.Open, FileAccess.Read);
Bitmap bmpFromFile = (Bitmap)System.Drawing.Image.FromFile(stream.Name);
if(Math.Round(bmpFromFile.HorizontalResolution) != 96 && Math.Round(bmpFromFile.VerticalResolution) != 96)
{
bmpFromFile.SetResolution(96, 96);
File.Delete(stream.Name); //This is where I get the error
bmpFromFile.Save($"{stream.Name}");
bmpFromFile.Dispose();
}
control.Image.Source = new BitmapImage(new Uri(stream.Name)); //assigning the new image here
//... more non-related code here
}
}
I'm stumped with this error. Am I doing something out of order? Many thanks in advance.