Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load an Image from a file without keeping the file locked?

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?

like image 893
RobH Avatar asked May 11 '11 08:05

RobH


2 Answers

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);
} 
like image 91
RobH Avatar answered Nov 15 '22 08:11

RobH


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
like image 24
F0r3v3r-A-N00b Avatar answered Nov 15 '22 09:11

F0r3v3r-A-N00b