微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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);
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。