PictureBox won't let me overwrite .bmp file

gamma4

New member
Joined
Apr 16, 2006
Messages
2
Programming Experience
Beginner
Hello,

I want to display a preview of an image on my form. I've been trying to do this with a PictureBox control, but have repeatedly run into the same problem.

The following code will draw the image I want (FYI sublayout is a proprietary API object that stores an image layout, and prev_pcbx is a PictureBox):

-snip-
Dim tempImage As Image
subLay.LayoutToFile(GenPath & "preview.bmp")
Prev_pcbx.Image = tempImage.FromFile(GenPath & "preview.bmp")
-snip-

However, when I run the same code again, I get a "preview.bmp is busy" message when subLay.LayoutToFile is called. I tried deleting the .bmp before this call, but then I get a message saying that the file is being used by another thread.

What can I do to remedy this issue?

Thanks in advance.
 
The documentation provided by Microsoft is really very useful. Here's a quote from the help topic for the Image.FromFile method:
The file remains locked until the Image object is disposed.
This means that you must either call Dispose on the Image object to release the file, which destroys the Image so it can not be used anymore, or else not lock the file in the first place by loading the image a different way. The .NET 2.0 PictureBox has a Load method that takes care of that but in previous versions this is your best bet:
VB.NET:
        Dim file As New IO.FileStream("file path here", IO.FileMode.Open)

        Me.PictureBox1.Image = Image.FromStream(file)
        file.Close()
 
Thanks

Thanks a lot.

Your filestream suggestion worked great.

I tried disposing of the Image object last night, but the Dispose method kept failing. I don't think I really understand the Image object well.

Again, thank for your help.
 
Back
Top