Tuesday, June 19, 2007

Image.FromFile locks the file

When you use the picturebox to display pictures and fill it by using

Picturebox1.Image = Image.FromFile("somefile"),

You will find that it locks the image file.

There are 2 solutions,

The first is to dispose of the image :

Picturebox1.Image.Dispose()

Wich is ok when you are going to put another picture in the picturebox but can lead to surprising results in other cases.

The second (and advised way) is to use a file stream :

Dim fs As System.IO.FileStream

fs = New System.IO.FileStream("somefile", IO.FileMode.Open, IO.FileAccess.Read)

PictureBox1.Image = System.Drawing.Image.FromStream(fs)

fs.Close()

No comments: