0

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.

user2529011
  • 705
  • 3
  • 11
  • 21
  • Sorry, but your code is a total mess. You aren't seriously setting an Image element's Source property in the setter of a view model property?? And why would you want to change the bitmap resolution at all, instead of simply adjusting the Image element's size? – Clemens Mar 11 '19 at 21:43
  • `System.IO.IOException: 'The process cannot access the file 'C:\MyAwesomeProjects\Resources\Button_A.png' because it is being used by another process.'` in your case means you're using this file in the current process. So you need to close/dispose all the stuff accessing the file before trying to delete it. In your case, I believe it is `stream`. – tukaef Mar 11 '19 at 21:47
  • 2
    @tukaef No, its the BitmapImage that keeps the file open. – Clemens Mar 11 '19 at 21:48

1 Answers1

0

According to the documentation System.Drawing.Image.FromFile Protects the file it is using until it is disposed of. Meaning you'll have to save the file with the proper name after you call bmpFromFile.Dispose();

I would suggest doing this by first saving this file into another temp folder used specifically to hold the new image before disposing the drawn image within your program. Store the location of this newly saved image as a string and simply move it into the original folder after deleting the original photo.

Let me know if that makes sense, I'm on my phone right now but I can type out the code for you if you need.

AdamTCox
  • 48
  • 7