I'm getting a generic GDI+ error when I save my Bitmap more than once. The complaint is that the Bitmap is being used by another process. I've tried manually closing, flushing, nullifying, and disposing the stream. Nothing I've tried has worked. Any ideas?

1 answers
When you reload the bitmap from the file, the file will remain locked until you dispose of the bitmap. This is probably why you're getting the errror when you try to resave it.
What you could try is to clone the bitmap (using Bitmap.Clone), call Dispose() on the original bitmap and then try and save the clone using the original file name.
You may need to leave a short interval to allow the file handle to be released before attempting to resave.
EDIT - suggested code
FURTHER EDIT
I found a Microsoft Support article on this problem and apparently, given the way GDI+ works, it's not sufficient just to clone the bitmap.
What you have to do instead is to create a new bitmap of the same size and pixel format as the first and then draw the original one onto it. When you call Dispose() on the original bitmap, the file will then be unlocked allowing you to save the new bitmap over it.
Assuming your original bitmap has a pixel format greater than 8 bpp, I followed the instructions in the article to come up with the following code. It seems to be working OK but, needless to say, I'd back up the file before you try it:
If you pass the bitmap to the method by reference, then you can keep a reference to the clone (if you need to) by assigning it back to the parameter as I've done above. If you don't need to keep a reference to the clone, I'd just call bitmap.Dispose() instead.
answered 2 years ago by:
17279
121
http://pastebay.com/83108 this did not work, am I doing what you suggested properly?
17279
Not quite - you need to dispose of the old bitmap before attempting to save the clone. I've amended my answer to include some revised code to try.
121
It's not working. I'm still getting a generic GDI+ error on that last line in the catch.
17279
I think I may have solved it. See my further edit above.
121
You have indeed solved it. Thank you for your help!