0

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.

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());
                } 

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

and also when tried method like

 profilePictureBox.Image = null;

i am getting below error

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

1 Answers1

0

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.

vane
  • 2,125
  • 1
  • 21
  • 40
  • The problem I have with this is a memory leak, if I use `PictureBox.Load` and `Dispose` of the old picture afterwards the memory consumption remains the same. If I use this method, even though I'm also disposing of the old image, the memory consumption increases for each image loaded. – Jay Croghan Jul 30 '22 at 07:56
  • I fixed this by calling `GC.WaitForPendingFinalizers()` and `GC.Collect()` - does this mean I can safely ignore calling the GC and eventually the garbage collector will do it's job anyway? – Jay Croghan Jul 30 '22 at 08:03