Question

I display an image using c# in a pictureBox. Then I want to change the image's name. I can't because I get that the image is being used by another process.

I open the image this way

 Image image1 = Image.FromFile("IMAGE LOCATION"); ;
        pictureBox1.Image = image1; 

Then try to change it's name this way and I get an IO exception saying " The process cannot access the file because it's being used by another process.

System.IO.File.Copy(@"OldName", @"NewName"); //copy changes name if paths are in the same folder

Isn't the object image1 holding the image? Why is the file still locked by the previous process? Any suggestions would be appreciated. Many thanks!

Was it helpful?

Solution

Have a look at this question: Free file locked by new Bitmap(filePath)

To free the lock you need to make a copy of the bits:

Image img;
using (var bmpTemp = new Bitmap("image_file_path"))
{
     img = new Bitmap(bmpTemp);
}

OTHER TIPS

Yes, picture box control locking IO file on the disk in that way.

If you want to rename linked file, you can:

  • or dispose picture box, and after rename the file (if this is suitable for your app)

  • or assign to the picture box a copy/clone of the image.

You can try this:

Image image1 = null;

using(FileStream stream = new FileStream("IMAGE LOCATION", FileMode.Open))
{
    image1 = Image.FromStream(stream);
}

pictureBox1.Image = image1

;

you need to dispose your image:

 Image image1 = Image.FromFile("IMAGE LOCATION"); ;
    pictureBox1.Image = image1;
 image1.Dispose();

the do the move.

this solution solved my problem. I was using a picturebox and loading its image directly from the disk without an intermediate image file. when I was done I was doing a "picturebox.dispose" and that did not free up the image file and I couldn't delete it because "file in use by vshost". I had to explicitly create an image variable (IE dim MyImage as image) and then first load the image into the image variable, then load MyImage into the picturebox. by having a reference to the image I could do a MyImage.dispose. That closed the link between vshost and the image and I was able to programmatically delete it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top