Use CacheOption = BitmapCacheOption.OnLoad
This option can be used with the BitmapImage.CacheOption
property or as an argument to BitmapDecoder.Create()
If you want to access multiple frames once the images is loaded you ll have to use BitmapDecoder.Create
. In either case the file will be loaded fully and closed.
See also my answer to this question
Update
The following code works perfectly for loading in all the frames of an image and deleting the file:
var decoder = BitmapDecoder.Create(new Uri(imageFileName), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
List<BitmapFrame> images = decoder.Frames.ToList();
File.Delete(imageFileName);
You can also access decoder.Frames after the file is deleted, of course.
This variant also works if you prefer to open the stream yourself:
List<BitmapFrame> images;
using(var stream = File.OpenRead(imageFileName))
{
var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
images = decoder.Frames.ToList();
}
File.Delete(imageFileName);
In either case it is more efficient than creating a MemoryStream
because a MemoryStream
keeps two copies of the data in memory at once: The decoded copy and the undecoded copy.