释放文件句柄.来自 BitmapImage 的 ImageSource [英] Release handle on file. ImageSource from BitmapImage
本文介绍了释放文件句柄.来自 BitmapImage 的 ImageSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何释放这个文件的句柄?
How can I release the handle on this file?
img 是 System.Windows.Controls.Image 类型
img is of type System.Windows.Controls.Image
private void Load()
{
ImageSource imageSrc = new BitmapImage(new Uri(filePath));
img.Source = imageSrc;
//Do Work
imageSrc = null;
img.Source = null;
File.Delete(filePath); // File is being used by another process.
}
<小时>
解决方案
private void Load()
{
ImageSource imageSrc = BitmapFromUri(new Uri(filePath));
img.Source = imageSrc;
//Do Work
imageSrc = null;
img.Source = null;
File.Delete(filePath); // File deleted.
}
public static ImageSource BitmapFromUri(Uri source)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = source;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
return bitmap;
}
推荐答案
在 MSDN 论坛上找到了答案.
Found the answer on MSDN Forum.
位图流不会关闭,除非缓存选项设置为BitmapCacheOption.OnLoad.所以你需要这样的东西:
Bitmap stream is not closed unless caching option is set as BitmapCacheOption.OnLoad. So you need something like this:
public static ImageSource BitmapFromUri(Uri source)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = source;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
return bitmap;
}
当你使用上面的方法得到一个 ImageSource 时,源文件将立即关闭.
And when you get an ImageSource using the method above, source file will be immediately closed.
这篇关于释放文件句柄.来自 BitmapImage 的 ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文