相信用過WPF的BitmapImage的,都在用類似這樣的代碼來解決文件無法刪除的問題!
如果看看msdn上簡單的描述,可以看到這樣的說明:
如果 StreamSource 和 UriSource 均設置,則忽略 StreamSource 值。
如果要在創建 BitmapImage 后關閉流,請將 CacheOption 屬性設置為 BitmapCacheOption.OnLoad。 默認 OnDemand 緩存選項保留對流的訪問,直至需要位圖並且垃圾回收器執行清理為止。
static class AppHelper
{
public static BitmapImage GetBitmapImage(string path)
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = new MemoryStream(File.ReadAllBytes(path));
bitmap.EndInit();
bitmap.Freeze();
return bitmap;
}
}
