【发布时间】:2012-04-25 16:06:23
【问题描述】:
如何释放这个文件的句柄?
img 是 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;
}
【问题讨论】:
-
不错的解决方案。你拯救了我的一天:)
-
这 3 行是什么:img.Source = imageSrc; //做工作 imageSrc = null; img.Source = null;
-
@MonsterMMORPG 不用担心它们... bitmap.CacheOption = BitmapCacheOption.OnLoad;是神奇的部分。