I wish to display an image in a PictureBox, loading the image from a file. The file gets overwritten periodically though, so I can't keep the file locked. I started by doing this:
pictureBox.Image = Image.FromFile( fileName );
However, this keeps the file locked. Then I tried to read through a stream:
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
pictureBox.Image = Image.FromStream(fs);
}
This doesn't lock the file, but does cause an exception to be thrown later on; MSDN indicates that the stream must be kept open for the lifetime of the image. (The exception includes a message that "A closed file may not be read" or similar.)
How can I load an image from a file, then have no further references to the file?
Sorry to answer my own question, but I thought this was too useful to keep to myself.
The trick is to copy the data from the file stream into a memory stream before loading it into an image. Then the file stream may be closed safely.
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
fs.CopyTo(ms);
ms.Seek(0, System.IO.SeekOrigin.Begin);
pictureBox.Image = Image.FromStream(ms);
}
For those working below Framework 4.0, here's what I did:
Using fs As New System.IO.FileStream(cImage, IO.FileMode.Open, IO.FileAccess.Read)
Dim buffer(fs.Length) As Byte
fs.Read(buffer, 0, fs.Length - 1)
Using ms As New System.IO.MemoryStream
ms.Write(buffer, 0, buffer.Length - 1)
picID.Image = Image.FromStream(ms)
End Using
End Using
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With