简体   繁体   中英

VB.NET How do I release an open file?

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

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()

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.

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()

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM