OpenFile对话框使资源保持打开状态

问题描述

使用“打开文件”对话框在应用程序中打开照片后,除非关闭应用程序,否则无法对该文件执行任何操作。我已将OpenFile对话框放在using语句中,并尝试了各种方法来释放资源,但均未成功。如何释放该进程以避免出现错误消息“该进程无法访问文件,因为该文件正在被另一个进程使用?

       using (OpenFileDialog GetPhoto = new OpenFileDialog())
        {
            GetPhoto.Filter = "images | *.jpg";
            if (GetPhoto.ShowDialog() == DialogResult.OK)
            {
                pbPhoto.Image = Image.FromFile(GetPhoto.FileName);
                txtPath.Text = GetPhoto.FileName;
                txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
                //GetPhoto.dispose();  Tried this
                //GetPhoto.Reset();  Tried this
                //GC.Collect(): Tried this
            }
        }

解决方法

Image.FromFile的文档所述:

该文件将保持锁定状态,直到处理完图像为止。

因此,您可以尝试制作图像的副本,然后发布原始的Image

using (OpenFileDialog GetPhoto = new OpenFileDialog())
{
    GetPhoto.Filter = "images | *.jpg";
    if (GetPhoto.ShowDialog() == DialogResult.OK)
    {
        using (var image = Image.FromFile(GetPhoto.FileName))
        {
            pbPhoto.Image = (Image) image.Clone(); // Make a copy
            txtPath.Text = GetPhoto.FileName;
            txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
        }
    }
}

如果没有帮助,您可以尝试通过MemoryStreamImage.FromStream方法进行复制:System.Drawing.Image to stream C#

,

您的问题不是(OpenFileDialog)您的问题是针对PictureBox
您可以使用this来加载图像,或者如果不起作用 为此加载图片

        OpenFileDialog GetPhoto = new OpenFileDialog();
        GetPhoto.Filter = "images | *.jpg";
        if (GetPhoto.ShowDialog() == DialogResult.OK)
        {
            FileStream fs = new FileStream(path: GetPhoto.FileName,mode: FileMode.Open);
            Bitmap bitmap = new Bitmap(fs);
            fs.Close(); // End using
            fs.Dispose();
            pbPhoto.Image = bitmap;
            txtPath.Text = GetPhoto.FileName;
            txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...