在C#中处理OpenFileDialog? [英] The dispose of an OpenFileDialog in C#?
问题描述
我已经搜索了整个堆栈溢出,但是找不到以下内容的答案:
I have searched throughout entire Stack Overflow, but I couldn't find an answer to the following:
使用 OpenFileDialog ,我打开的文件将被阻止在我的程序中使用,直到我关闭程序.因此,如果我打开一个图像,则不再可以在我的 Windows&Explorer 中替换该图像
When I'm using my OpenFileDialog, the files I open get blocked for use out of my program until I close my program. So if I open an image, I am not allowed to replace that image in my Windows Explorer anymore.
我认为这与处理OpenFileDialog有关,但我不确定如何解决...
I think this is a problem with disposing my OpenFileDialog, but I'm not sure how to solve it...
我的代码:
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Title = "Open Image";
ofd.Filter = "PNG Image(*.png|*.png" +
"|GIF Image(*.gif|*.gif" +
"|Bitmap Image(*.bmp|*.bmp" +
"|JPEG Compressed Image (*.jpg|*.jpg";
if (ofd.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd.FileName);
}
}
我认为using
块可以解决此问题,但是不...它仍然被程序使用.我想将图片加载到图片框中,然后希望该图片再次可用(以便我可以重命名,替换它,等等...).
I thought that the using
block would solve this problem, but nope... It still gets used by the program. I want to load the image in the picturebox and then I want the image to be available again (so I can rename it, replace it, etc...).
推荐答案
如克里斯所写,请尝试以下方法:
As written by Chris, try something like:
pictureBox1.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(old.FileName)));
它使用File.ReadAllBytes
读取所有文件,将其放在MemoryStream
中,然后将MemoryStream
传递给Image
静态初始值设定项.
It reads all the file with File.ReadAllBytes
, put it in a MemoryStream
and pass the MemoryStream
to the Image
static initializer.
等同于:
byte[] bytes = File.ReadAllBytes(old.FileName);
MemoryStream ms = new MemoryStream(bytes);
pictureBox1.Image = Image.FromStream(ms);
您不得处置MemoryStream
!如果/当处置Image
时,将终止MemoryStream
的终结器(如果您没有其他引用ms
的内容),并且处置MemoryStream
(请注意,这不是必需的)这将立即发生...这将在GC运行时发生)
You mustn't dispose the MemoryStream
! If/when the Image
will be disposed, the finalizer of MemoryStream
will kick in (if you don't have other references to ms
) and the MemoryStream
will be disposed (note that this isn't something that will happen immediately... It's something that will happen when the GC will run)
这篇关于在C#中处理OpenFileDialog?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!