Question Can't delete image files after viewing them in program

Robert Homes

Member
Joined
Nov 16, 2023
Messages
11
Programming Experience
5-10
I have a procedure that scans through a collection of images I use for tiled backgrounds to see which ones I need to delete or rename. However, once the program has looked at an image, it won't delete or rename the image file.
 
This seems to be a common approach:
VB.NET:
Using img = Image.FromFile("N:\test.png")
    PictureBox1.Image = New Bitmap(img)
End Using
 
Didn't help. Still get the same message that the file is "being used by another process". Maybe I should have mentoned this before -- the image I'm using is for the BACKGROUND of a picture box. Maybe that makes a difference. (ps, Well, I did mention it before, but i didn't stress it enough.)
 
You're doing something wrong. We can't see what you're doing wrong if we can't see what you're doing. ALWAYS provide the relevant code.

If you create an Image object from a file then that file is locked until you dispose the Image. Are you trying to delete the file while the app is still displaying the Image? If not then you need to call Dispose on the Image when you're done with it in order to release the file. If so then you need to create an Image that won't lock the file. That could be done like this:
VB.NET:
Dim finalImage As Image

Using tempImage = Image.FromFile(filePath)
    finalImage = New Bitmap(tempImage)
End Using

'Use finalImage here.'
That will open the file and lock it, create a copy of the Image and then dispose the original, which will release the file. I've never actually used that constructor but I think it should work that way. What I've seen done before is creating a Bitmap of the same dimensions and then drawing the original onto it. That would have the same effect but this is simpler, assuming it works as expected.
 
Back
Top