c# Image from file close connection
Asked Answered
L

5

5

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!

Luckily answered 29/11, 2012 at 12:15 Comment(0)
S
11

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);
}
Snowstorm answered 29/11, 2012 at 12:19 Comment(0)
M
3

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.

Mccabe answered 29/11, 2012 at 12:17 Comment(0)
F
3

You can try this:

Image image1 = null;

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

pictureBox1.Image = image1

;

Flores answered 29/11, 2012 at 12:24 Comment(1)
@HamletHakobyan - According to the answer in the linked question, it sometimes works ans sometimes not. My guess is that, for instance depending of the size of the file, not the entire file is read when using a stream.Snowstorm
H
2

you need to dispose your image:

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

the do the move.

Helenehelenka answered 14/2, 2015 at 1:8 Comment(0)
W
0

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.

Workout answered 9/2, 2017 at 4:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.