打开文件对话框保持资源打开

OpenFile Dialog Box keeps resources open

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

The file remains locked until the Image is disposed.

所以您可以尝试制作图像的副本,然后发布原始图像 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 method: 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);
        }