在C#中处理OpenFileDialog? [英] The dispose of an OpenFileDialog in C#?

查看:125
本文介绍了在C#中处理OpenFileDialog?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了整个堆栈溢出,但是找不到以下内容的答案:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆