Reputation:
I'm opening a file called tempImage.jpg and showing it on a form in a PictureBox. I then click a button called Clear and the file is removed from the PictureBox using PictureBox2.Image = Nothing, however I'm unable to delete the file as it is locked open. How can I release it so I can delete it? I'm using VB.NET and a forms app.
Thanks
Upvotes: 1
Views: 35326
Reputation: 3912
As i can't comment yet (not enough experience points), this is an answer for the above "is there a equivalent to using in vb.net"
Yes, in .Net 2.0 and above you can use "Using". In .Net 1.0 and 1.1 however, you would need to dispose if the object in the finally block
Dim fs As System.IO.FileStream = Nothing
Try
'Do stuff
Finally
'Always check to make sure the object isnt nothing (to avoid nullreference exceptions)
If fs IsNot Nothing Then
fs.Close()
fs = Nothing
End If
End Try
Adding the closing of the stream in the finally block ensures that it will get closed no matter what (as opposed to the connection getting opened, a line of code bombing out beneath before the stream is closed, and the stream staying open and locking the file)
Upvotes: 0
Reputation: 11702
is there a equivalent to using in vb.net
this is what i would do in c#
using( filestream fs = new filestream)
{
//whatever you want to do in here
}
//closes after your done
Upvotes: 0
Reputation: 11773
take control of the file
'to use the image
Dim fs As New IO.FileStream("c:\foopic.jpg", IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = Image.FromStream(fs)
'to release the image
PictureBox1.Image = Nothing
fs.Close()
Upvotes: 1
Reputation: 1500575
When you use PictureBox2.Image = Nothing
you're waiting for the garbage collector to finalize the resource before it releases it. You want to release it immediately, so you need to dispose of the image:
Image tmp = PictureBox2.Image
PictureBox2.Image = Nothing
tmp.Dispose()
Upvotes: 7
Reputation: 185643
If you're using Image.FromFile, you need to call .Dispose() on the image. When you go to clear it out, do something like...
Image currentImage = pictureBox.Image
pictureBox.Image = Nothing
currentImage.Dispose()
That will release the file.
Upvotes: 3