10

This seems like a fairly simple issue, but I can't seem to figure a way to work around it.

In a WPF window I have an image, image_small_pic. In the associated C# file I set the value of that using this code:

Uri src = new Uri(image_source, UriKind.RelativeOrAbsolute);
small_image_bmp = new BitmapImage(src);
image_small_pic.Source = small_image_bmp;

Where small_image_bmp is a public BitmapImage object. But then if then, later on, if I change small_image_bmp to another file and reassign image_small_pic.Source, then the original image is still locked and I can't delete it. Even if I try later it's still locked. Any thoughts how I can free this up?

cost
  • 4,420
  • 8
  • 48
  • 80

2 Answers2

14

Check out this article. There's some odd behaviour with WPF images that you're coming across. The solution is to read in the bytes yourself and then create an image based on them, since if you let the framework handle it, the file will remain locked.

dlev
  • 48,024
  • 5
  • 125
  • 132
  • Looks like that fixed it, thanks! What an odd solution, but certainly one that works. – cost Aug 17 '11 at 15:02
3
Uri src = new Uri(image_source, UriKind.RelativeOrAbsolute);
var small_image_bmp = new BitmapImage();
small_image_bmp.BeginInit();
small_image_bmp.CacheOption = BitmapCacheOption.OnLoad;
small_image_bmp.UriSource = src;
small_image_bmp.EndInit();

image_small_pic.Source = small_image_bmp;
Suhas Deshpande
  • 715
  • 1
  • 6
  • 17