This entry was posted on Friday, February 3rd, 2012 at 3:51 pm and is filed under Tech Stuff. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.
Q: How can I stop BitmapImage, in .NET Windows Presentation Foundation (WPF) from locking the source image file?
A: By default BitmapInfo seems to lock the source image file so that you can use the bitmapinfo object and modify or delete the source file at the same (or similar) time. For example, this C# will probably yield a locked image file:
var bitmap = new BitmapImage(new Uri(imageFilePath));
// use bitmap…
// use bitmap…
You can get around this locking problem as follows, it’s a little bit more long-winded but it worked for us….
var bitmap = new BitmapImage();
var stream = File.OpenRead(imageFilePath);
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
stream.Close();
stream.Dispose();
// Use bitmap…..
var stream = File.OpenRead(imageFilePath);
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
stream.Close();
stream.Dispose();
// Use bitmap…..
