views:

201

answers:

1

I have this code:

Dim xx as image
xx = image.fromfile(Fileloc)
picturebox.image = xx

And i can't delete the file even though I've loaded it into a picture box. If I add this line:

xx.dispose

the picture box becomes a big red X.

I only want to delete the images when my application is closing (they are temp files). So shall I just dispose them before I delete them?

+4  A: 

Don't use Image.FromFile, it keeps the file open.

From MSDN :

The file remains locked until the Image is disposed.

Do that instead :

Dim xx as Image
Using str As Stream = File.OpenRead(Fileloc)
    xx = Image.FromStream(str)
End Using
picturebox.Image = xx

The file is closed after the image is loaded, so you can delete the file if you need to

Thomas Levesque
That doesn't help, it is still associated with the same file.
Hans Passant
No, it's not... the Image is only associated with the stream, which is closed at the end of the Using block. It doesn't even know the filename... I've used this technique for some time and I'm certain it works fine.
Thomas Levesque
Maybe str.Close()
Rick Ratayczak
It's done implicitly at the end of the Using block (actually it calls Dispose, which in turn calls Close)
Thomas Levesque