VB.Net: Problem deleting an image used by a PictureBox

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • krungkrung
    New Member
    • Nov 2008
    • 18

    VB.Net: Problem deleting an image used by a PictureBox

    hi again to everyone!

    I made a simple program(for my VB.Net practice). The program loads an image file to a picturebox upon clicking a button. after loading the image file i have another button to delete the loaded image file from the directory. But I have a problem deleting the image file used by the picturebox even if I set the "PictureBox1.Im age = Nothing" before deletion takes place. The error says, "The process cannot access the file because it is being used by another process". What must be the problem with this? can somebody give me an Idea how will i deal with this problem?

    Here's my code on delete process:

    Code:
    Private Sub RemoveFromDirectory(ByVal strFile As String)
    
            Dim strDirectory As String
    
            strDirectory = Application.StartupPath & "\Images"
    
                If File.Exists(strDirectory & "\" & strFile & ".jpg") = True Then
                    PictureBox1.Image = Nothing
                    File.Delete(strDirectory & "\" & strFile & ".jpg")
                End If
    
    End Sub
    **strDirectory --> the image file loaded on a pic box
  • nukefusion
    Recognized Expert New Member
    • Mar 2008
    • 221

    #2
    When you load an image into a picturebox that file is indeed locked. The lock will probably maintain until, in development, you restart your IDE, or in a release environment, your app is restarted.
    To get around this, load the image from a file stream object as per the following example:

    Code:
    Dim fs As System.IO.FileStream
    ' Specify a valid picture file path on your computer.
    fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg", 
         IO.FileMode.Open, IO.FileAccess.Read)
    PictureBox1.Image = System.Drawing.Image.FromStream(fs)
    fs.Close()
    The filestream object should release the lock on the image once closed.

    Comment

    • krungkrung
      New Member
      • Nov 2008
      • 18

      #3
      yeah it works! thanks a lot nukefusion!

      Comment

      • Ahmed Volcano
        New Member
        • Mar 2012
        • 1

        #4
        Thanks bro , this really helped me

        Comment

        • roberto1959
          New Member
          • Apr 2013
          • 1

          #5
          do the following

          ceate a batch file like

          del <file_name>

          name it clear.bat

          when you leave your program call it using shell clear.bat

          it works in vb 2010

          Comment

          • Jaylala03
            New Member
            • Oct 2014
            • 1

            #6
            yeah it works! thanks a lot !

            Comment

            Working...