c# - File.Delete on bitmap doesn't work because the file is being used by another process (I used bitmap.Dispose();) -
i'm creating windows forms application in c#.
i have buttons on form , used backgroundimage property set bitmap images on them.
i wanted change images dynamiclly so:
i used
using (bitmap = new bitmap...), saved new bitmap picture.i assign new bitmap on button.
then, tried delete old bitmap calling
dispose(),system.io.file.delete(nametodelete);
the problem: file.delete function throws exception: "file being used process" , can't delete it.
i tried calling gc.collect() , assigning bitmap null didn't work.
the "solution" find call thread.sleep(2) before deleting, it's patch , doesn't work each time.
here code (layerpics[z] array holds bitmaps, 1 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 do? thanks!
it's not bitmap causes problem, line:
buttons.backgroundimage = image.fromfile(name); here, create instance of image class using factory method fromfile(). file remains locked until image disposed.
this the reference.
Comments
Post a Comment