在加载另一张图片之前删除Picture Box中的文件 [英] Delete file which was in Picture Box before loading another Picture

查看:171
本文介绍了在加载另一张图片之前删除Picture Box中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有图片框,当用户在图片框上加载图片中的旧文件时,我会尝试编写代码。我试图找到24小时的解决方案仍然无法找到完全可行的解决方案。

I have picturebox and i trying write code when the users loads another image on picturebox the old file which was in picture to be deleted. I trying to find solution for for 24 hrs still i didn't able find fully working solution.

我提出了1个部分解决方案,以下是部分代码

I came up with 1 partial solution and following is partial code

 profilePictureBox.Dispose(); // When I use This After The Function Executed
                                 PictureBox Disappears But File Delete Successfully.
 try
                {
                    if (File.Exists(oldfilename))
                    {
                        File.Delete(oldfilename);
                        profilePicPictureBox.Load(picPath);
                    }
                    else
                    {
                        MessageBox.Show("File Not Found");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                } 

旧文件名将包含要删除的先前文件名,picPath将包含选择图像用户的新路径。

"old filename" will contain previous filename to delete and "picPath" will contains new path of image user chosen.

以及尝试过的方法

 profilePictureBox.Image = null;

我收到以下错误

System.IO.IOExecption:The Process cannot access the file 
'filepath' because it is being      used by another process.


推荐答案

您需要将图像加载到内存中并添加它到图片框而不直接从文件加载它。 加载函数使文件保持打开状态,您将无法删除它。试试这个。注意:此代码中没有错误检查。

You need to load the image into memory and add it to the picture box without loading it directly from a file. the Load function keeps the file open and you won't be able to delete it. Try this instead. NOTE: there is no error checking in this code.

using (FileStream fs = new FileStream("c:\\path\\to\\image.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    byte[] buffer = new byte[fs.Length];
    fs.Read(buffer, 0, (int)fs.Length);
    using (MemoryStream ms = new MemoryStream(buffer))
        this.pictureBox1.Image = Image.FromStream(ms);
}

File.Delete("c:\\path\\to\\image.jpg");

这将打开文件并将其内容读入缓冲区然后关闭它。它将加载带有复制字节的内存流的图片框,允许您自由删除它加载的图像文件。

This will open the file and read its contents into a buffer then close it. It will load the picture box with the memory stream full of "copied" bytes, allowing you to freely delete the image file it was loaded from.

这篇关于在加载另一张图片之前删除Picture Box中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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