如何从文件加载图像而不保持文件锁定?
我希望在 PictureBox 中显示图像,从文件加载图像。不过,该文件会定期被覆盖,因此我无法保持文件锁定。我首先这样做:
pictureBox.Image = Image.FromFile( fileName );
但是,这会使文件保持锁定状态。然后我尝试读取一个流:
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
pictureBox.Image = Image.FromStream(fs);
}
这不会锁定文件,但确实会导致稍后抛出异常; MSDN 指出流必须在图像的生命周期内保持打开状态。 (例外情况包括“可能无法读取已关闭的文件”或类似消息。)
如何从文件加载图像,然后不再引用该文件?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很抱歉回答我自己的问题,但我认为这太有用了,不适合自己保留。
诀窍是在将数据加载到图像中之前将数据从文件流复制到内存流中。然后可以安全地关闭文件流。
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.
对于那些在 Framework 4.0 以下工作的人,这就是我所做的:
For those working below Framework 4.0, here's what I did: