【问题标题】:OpenFile Dialog Box keeps resources openOpenFile 对话框保持资源打开
【发布时间】:2020-09-21 14:24:38
【问题描述】:

使用打开文件对话框在我的应用程序中打开照片后,除非我关闭我的应用程序,否则我无法对文件执行任何操作。我已将 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
            }
        }

【问题讨论】:

    标签: c# openfiledialog


    【解决方案1】:

    您的问题不是 (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);
            }
    

    【讨论】:

    • 谢谢!我很欣赏对实际问题的解释。这行得通。
    • 使用此代码时出现问题。当我尝试将图像保存到我的 SQL DB 时,我现在得到一个错误。我保存图像的代码是 MemoryStream stream = new MemoryStream(); pbPhoto.Image.Save(流,System.Drawing.Imaging.ImageFormat.Jpeg); byte[] pic = stream.ToArray();
    • 查尔斯,如果您需要更多帮助,这是我的电子邮件 amirhoseinadlfar@gmail.com
    【解决方案2】:

    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#

    【讨论】:

    • 为什么需要复制图片?我假设只使用带有图像的 using 语句就可以解决问题......
    • @Chrisi Image 是一个类(即引用类型)。当它分配给pbPhoto.Image 属性然后被释放时,对该属性的访问会导致ObjectDisposedException
    猜你喜欢
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多