C# 在加载另一张图片之前删除图片框中的文件

C# 在加载另一张图片之前删除图片框中的文件,c#,winforms,io,picturebox,C#,Winforms,Io,Picturebox,我有picturebox,当用户在picturebox上加载另一个图像时,我尝试编写代码,这是要删除的图片中的旧文件。我24小时都在努力寻找解决方案,但仍然无法找到完全有效的解决方案 我提出了1个部分解决方案,下面是部分代码 profilePictureBox.Dispose(); // When I use This After The Function Executed PictureBox Disappears But F

我有picturebox,当用户在picturebox上加载另一个图像时,我尝试编写代码,这是要删除的图片中的旧文件。我24小时都在努力寻找解决方案,但仍然无法找到完全有效的解决方案

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

 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”将包含用户选择的图像的新路径

而且当你试过这种方法的时候

 profilePictureBox.Image = null;
我正在犯错误

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

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

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");
这将打开文件并将其内容读入缓冲区,然后关闭它。它将加载图片框,内存流中充满“复制”字节,允许您自由删除从中加载的图像文件