Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Image.FromFile locks file

Status
Not open for further replies.

HANSGIELEN

Programmer
Mar 6, 2003
6
0
0
DE
When loading an image with Image.FromFile the picturebox control locks the file so you get an exception when you try to delete it.

After long research I found the following solution, does anybody know something more elegant?

If Not (myPic.Image Is Nothing) Then
'get rid of any former image
myPic.Image.Dispose()
myPic.Image = Nothing
End If
myPic.Image = GetPicture("C:\Test\Sample.JPG")

Function GetPicture(ByVal filename As String) As Image
Dim eMsg As String
Dim sStream As FileStream
Dim mStream As MemoryStream
Dim sReader As BinaryReader
Dim BytesRead() As Byte

Try
'open filestream
sStream = New FileStream(filename, FileMode.Open, FileAccess.Read)

'declare memory stream in correct size
mStream = New MemoryStream(sStream.Length)

'create binary reader for file stream
sReader = New BinaryReader(sStream)

'read filestream to bytearray
BytesRead = sReader.ReadBytes(sStream.Length)

'write bytearray to memory stream
mStream.Write(BytesRead, 0, sStream.Length)

'create an image from the memory stream
GetPicture = New Bitmap(mStream)

'Cleanup
sStream.Close()
mStream.Close()
sReader = Nothing
sStream = Nothing
mStream = Nothing
Catch ex As Exception
eMsg = "Error in GetPicture" + vbCrLf + vbCrLf
eMsg = eMsg + ex.ToString
MsgBox(eMsg, MsgBoxStyle.Exclamation)
End Try
End Function
 
I don't know about elegance, but what about this?

1: Copy the file to another location (such as Temporary Internet Files)

2: Open the copy

3: If you save/overwrite (rather than Save As...), just copy the file back to its original location.

Ben

There's no place like 127.0.0.1.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top