I'm creating a Windows Forms Application in C#.
I have some buttons on the form and I used the BackgroundImage
property to set bitmap images on them.
I wanted to change those images dynamiclly so:
I used using (bitmap = new Bitmap...)
and saved a new bitmap picture.
I assign the new bitmap to be on the button.
Then, I tried to delete the old bitmap by calling Dispose()
and then System.IO.File.Delete(nameToDelete)
;
The problem: the File.Delete
function throws an exception: "file is being used by another process" and I can't delete it.
I also tried calling GC.Collect()
and assigning the bitmap to null
but it didn't work.
The only "solution" I find is to call Thread.Sleep(2)
before deleting, But it's a patch and doesn't work each time.
Here is the code (layerPics[z] is an array that holds all the bitmaps, one for each button):
string name = "new name";
Bitmap bitmap;
using (bitmap = new Bitmap(x, y))
{
Form.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(name);
button.BackgroundImageLayout = ImageLayout.Stretch;
button.BackgroundImage = Image.FromFile(name);
}
layerPics[z].Dispose();
layerPics[z] = null;
layerPics[z] = bitmap;
What can I do? Thanks!
It's not the Bitmap
that causes the problem, but this line:
Buttons.BackgroundImage = Image.FromFile(name);
Here, you create an instance of an Image
class using the factory method FromFile()
. The file remains locked until the Image
is disposed.
This is the reference.