Search code examples
c#visual-studio-2010bitmapdisposedelete-file

File.Delete on bitmap doesn't work because the file is being used by another process (I used bitmap.Dispose();)


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:

  1. I used using (bitmap = new Bitmap...) and saved a new bitmap picture.

  2. I assign the new bitmap to be on the button.

  3. 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!


Solution

  • 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.