I've got a form in a MDI project that contains a picturebox control. I populate the control like this...
newimage = Image.FromFile(
"c:\temp.bmp")Me.PictureBox1.Image = newimage
I need to later kill the file "c:\temp.bmp", but even after executing the dispose method of the picturebox control I get the error "The process cannot access the file 'c:\temp.bmp' because it is being used by another process." What am I missing here?
Any help would be greatly appreciated.
Thanks,
Cam
CamPosted May 22, 2008, 7:07 PM
Beautiful Scott!
I actually was going down that road initially, as the dll that generated the temp file had a function that wrote to file stream, but it had compatability problems with VB filenumber, it required a filehandle.
Thanks very much.
Scott LyslePosted May 22, 2008, 5:20 AM
Open it from a memory stream rather than from the file; once you dispose of the memory stream and can delete the source file at will (here is an example with a form, picturebox, and a button, the image is loaded at form load, the button click event deletes the file after setting the picturebox image to nothing (which is not required, you can leave the image showing and still delete the image file):
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim fsImage As System.IO.FileStream = Nothing
fsImage = System.IO.File.Open("c:/Temp/junk.bmp", FileMode.Open, FileAccess.Read)
Dim bArrImage(fsImage.Length) As Byte
fsImage.Read(bArrImage, 0, Convert.ToInt32(fsImage.Length))
fsImage.Close()
Dim ms As New MemoryStream(bArrImage)
PictureBox1.Image = Image.FromStream(ms)
ms.Dispose()
Catch ex As IOException
MessageBox.Show(ex.Message, "Error Opening Image")
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Opening Image")
End Try
End Sub
' clear the picturebox and delete the source image
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
' you don't have to clear the image first but if you
'want to, just set the image to nothing
PictureBox1.Image = Nothing
' delete the source file used to
' populate the picture box image
System.IO.File.Delete("c:/Temp/junk.bmp")
' disable the button after the image
' is gone
Button1.Enabled = False
Catch ex As IOException
MessageBox.Show(ex.Message, "Error Disposing of Image")
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Disposing of Image")
End Try
End Sub
End Class