2

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

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
Gary
  • 495
  • 3
  • 11
  • 21

1 Answers1

4

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);
}
daryal
  • 14,643
  • 4
  • 38
  • 54
  • I tried that, it makes no difference. I also disabled the use of vshost.exe, but then it just gets locked by the application itself. – Gary May 11 '12 at 12:40
  • This will still give errors when manipulating images opened this way, though. If they're opened from a backing resource (like a file _or_ a stream), they will _always_ assume that that resource still exists. The only way around this is [a deep clone of the image data](https://stackoverflow.com/a/48170549/395685) – Nyerguds Jan 24 '18 at 13:15