I have a program that creates a bitmap, and saves it as a .jpg file.

All works great, except if in the program i want to delete this newly created file without first restarting the application. An exception is thrown saying that the file is in use, even if i have disposed the image from the picturebox on the screen and within the code that created the image!

Here is an example of the code:

Private sub CreateImage()

Dim i1 As System.Drawing.Image

i1 = System.Drawing.Image.FromFile("FileName")

Dim w As Integer = 88
Dim h As Integer = 72
Dim b1 As New System.Drawing.Bitmap(w, h, PixelFormat.Format24bppRgb)

Dim g1 As Graphics = Nothing

g1 = Graphics.FromImage(b1)

g1.DrawImage(i1, New Rectangle(0, 0, 88, 72), New Rectangle(0, 0, i1.Width, i1.Height), GraphicsUnit.Pixel)

g1.InterpolationMode = Drawing.Drawing2D.InterpolationMode.High

g1.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias

b1.Save("NewImage.jpg", Imaging.ImageFormat.Jpeg)

b1.Dispose()

g1.dispose()

End sub


Private sub DeleteImage()

File.Delete("NewImage.jpg")
End Sub

It looks as if the image is not being released from memory, even though i dispose it.

I have also tried b1 = Nothing and g1 = Nothing and i1 = Nothing

Any help is much appreciated.