Friday, April 29, 2011

VB.NET How do I release an open file?

Hi all,

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

From stackoverflow
  • 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.

  • 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()
    
    Andrew Hare : +1 For explaining *why* it works.
  • 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 eqivlant to using in vb.net

    this is what i wuold do in c#

    using( filestream fs = new filestream)
    {
    
    //whatever you want to do in here
    
    
    }
    
    //closes after your done
    

    I

  • As i cant comment yet (not enough experience points), this is an answer for the above "is there a eqivlant 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 a finall 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 Not fs Is 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)

0 comments:

Post a Comment