且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-07-10 01:00:03

很抱歉回答我自己的问题,但是我认为这对保持自己的价值太有用了.

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