Home » Programming » C# » vb.net Bitmap object locks images (impossible to move/delete jpg/gif files) – .Dispose() Method common problem

vb.net Bitmap object locks images (impossible to move/delete jpg/gif files) – .Dispose() Method common problem

posted in: ASP.NET, C#, Programming, VB.Net 0

Many people are in trouble and on forums asking why the .Net Bitmap object does not release an image with its .Dispose() method. The Bitmap object (after its destruction too) seems to lock the image file, then we are not able to move or delete that image file through the file system.

This is a known problem and it occurs when we declare and instantiate a Bitmap object and destruct that like in the following code:

[sourcecode language=”vb”]

‘create a bitmap object
Dim myBitmap As New Bitmap("c:myimage.jpg")

‘editing image routines, right here
‘…


‘release all Bitmap object resources
myBitmap.Dispose()

[/sourcecode]

The above code it is formally correct, however in same circumstances the .net garbage collector cannot recognize bitmap’s disposing; Dispose() method leaves the image file in an unusable state, then as MSDN said, we MUST release explicitly any reference after a Dispose() call;

with the following code, You will not encounter any problem, and after Dispose() You can edit, move, delete the image file by the filesystem functions…

[sourcecode language=”vb”] ‘create a bitmap object
Dim myBitmap As New Bitmap("c:myimage.jpg")

‘editing image routines, right here
‘…

‘release image reference
While myBitmap IsNot Nothing
myBitmap.Dispose()
myBitmap = Nothing ‘<– tells .net garbage collector to release resources
End While

[/sourcecode]

Happy image editing! 🙂


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.