Question

I have a c# application which shows images in a form. I'm trying to overwrite these images and regenerate them. I get an exception while I'm trying to delete an existing image (it's a png in this case). I tried disposing the image that the picturebox is using and then setting it to null, but I still get an exception due to a sharing violation. Nevertheless, I can go to explorer and delete the file without any problem.

In trying to figure out what process has this image locked, Process Monitor tells me it's the vhost.exe which is hosting my application.

How can I get around this? Is there some way I can get the host to release the lock on the file so that I can delete/recreate it? Ultimately I have large number of images which are generated as thumbnails which would need updating anytime my database incurs changes which affect the graphics. I'd hate to think I need to call a command shell to do this.

Thanks for any advice.

Gary

Was it helpful?

Solution

You can try loading images using file streams and closing them after reading.

FileStream fileStream = new FileStream("ImageName.jpg", FileMode.Open, FileAccess.Read);
yourPictureBox.Image = Image.FromStream(fileStream);
fileStream.Close();

Or instead of explicitly closing; you can employ using statement;

using(FileStream fileStream = new FileStream("ImageName.jpg", FileMode.Open, FileAccess.Read))
{
    yourPictureBox.Image = Image.FromStream(fileStream);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top