Mahmoud Sami
Mahmoud Sami

Reputation: 55

vb.net delete file used by another process

I Have here a simple code :

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Button 1
    PictureBox1.Image = Image.FromFile("D:\1.jpg")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    'Button 2
    PictureBox1.Image = Nothing
    IO.File.Delete("D:\1.jpg")
End Sub

When i press button 1 to import an image from file then i wanted to delete this image after press button 1 there is an error "The process cannot access the file 'D:\1.jpg' because it is being used by another process."

that error happen when i press button 2 , any solution ?


(Edited) : Solution Here unable to delete image after opening it in vb.net app

Upvotes: 0

Views: 8118

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54487

The Image.FromFile method locks the file until the Image object is disposed. Setting the Image property of a PictureBox to Nothing does not dispose the Image object. You need to do that explicitly:

PictureBox1.Image.Dispose()
PictureBox1.Image = Nothing
IO.File.Delete("D:\1.jpg")

Upvotes: 3

Related Questions