如何在不锁定文件的情况下从文件加载图像?

问题描述:

我希望在PictureBox中显示图像,并从文件中加载图像.不过,该文件会定期被覆盖,因此我无法保持文件锁定.我首先这样做:

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);
} 

这不会锁定文件,但是确实会导致以后引发异常. MSDN指示在图像的生命周期内,流必须保持打开状态. (该例外包括可能无法读取关闭的文件"或类似消息的消息.)

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);
}