在加载另一张图片之前删除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.