Removing an Image Used by a WPF Control

I would like to associate the image with some control, delete it later.

path = @"c:\somePath\somePic.jpg"
FileInfo fi = new FileInfo(path);
Uri uri = new Uri(fi.FullName, UriKind.Absolute);
var img = new System.Windows.Controls.Image();
img.Source = new BitmapImage(uri);

Now after this code, I would like to delete the file:

fi.Delete();

But I can’t do this because the image is being used now. Between a piece of code 1 en 2 what can I do to release it?

+5
source share
2 answers

copy the image to a MemoryStream before giving the image source this should look like this.

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 30;
bi.StreamSource = byteStream;
bi.EndInit();

where byteStream is a copy of the file in MemoryStream

as this can be useful

+3
source

MemoryStream, , : MemoryStream, , , , MemoryStream , .

- BitmapCacheOptions.OnLoad:

path = @"c:\somePath\somePic.jpg"

var source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();  // Required for full initialization to complete at this time

var img = new System.Windows.Controls.Image { Source = source };

.

. , , , CreateOption = BitmapCreateOption.IgnoreImageCache. MemoryStream, .

+11

All Articles