BmpBitmapEncoder lock files on disk after reading Bitmap from file
I have Image Control in xaml file:
<Image Height="100" Source="file:///c:/imageShape.bmp" Margin="184,288,0,0" Width="100" HorizontalAlignment="Left" Name="image1" VerticalAlignment="Top" />
I load this xaml file byXamlReader.Load. After that I try to save bitmap into another file:
System.Windows.Controls.Image
imageControl = ....BmpBitmapEncoder bmpBitmapEncoder =newBmpBitmapEncoder();BitmapFrame bitmapFrame =BitmapFrame.Create(imageControl.SourceasBitmapSource);bmpBitmapEncoder.Frames.Add(bitmapFrame);
MemoryStream stream =newMemoryStream();using (FileStream fs =File.Create("t:\\out.bmp")){
bmpBitmapEncoder.Save(fs);
}
So, after ".Save(fs)" original bitmap file (c:\imageShape.bmp) is locked and I can't delete it until I close the process. How can I unlock this file?
The trick is to change how the image is loaded into memory. By default, the image bits will be lazily loaded. In that case, we're never sure when we've got all the bits out, so we need to retain a lock on the file. To suck all the bits out on load, specify the OnLoad cache option:
<Image Margin="184,288,0,0" Width="100" HorizontalAlignment="Left" Name="image1" VerticalAlignment="Top" >
<Image.Source>
<BitmapImage UriSource="tulip.jpg" CacheOption="OnLoad"/>
</Image.Source>
</Image>
Say that Image object is dynalically detached from its parent (so it's not in memory anymore) and that you don't want to use OnLoad, how can be forced the file unlocking?
I've seen that if you detach the image and delete the file, it fails.
But if you detach the image, let the dispatcher work for a while and then delete the file, it works.
What should I do between detaching and deleting the file?
TIA