2012-04-25 65 views
22

如何释放此文件上的句柄?释放文件上的句柄。来自BitmapImage的ImageSource

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; 
} 
+1

不错的解决方案。你救了我的一天:) – gisek 2013-01-05 20:43:59

+0

这3行是什么:img.Source = imageSrc; //做工 imageSrc = null; img.Source = null; – MonsterMMORPG 2013-03-27 11:43:13

+0

@MonsterMMORPG不用担心它们... bitmap.CacheOption = BitmapCacheOption.OnLoad;是神奇的一部分。 – NitroxDM 2014-04-30 20:15:21

回答

24

发现在MSDN论坛答案。

除非高速缓存选项设置为 BitmapCacheOption.OnLoad,否则位图流不会关闭。所以,你需要的东西是这样的:

public static ImageSource BitmapFromUri(Uri source) 
{ 
    var bitmap = new BitmapImage(); 
    bitmap.BeginInit(); 
    bitmap.UriSource = source; 
    bitmap.CacheOption = BitmapCacheOption.OnLoad; 
    bitmap.EndInit(); 
    return bitmap; 
} 

而当你使用上述方法得到的ImageSource,源文件 将被立即关闭。

see MSDN social forum

+0

对你很好。 – NitroxDM 2012-04-25 16:26:29

+0

如果我使用这段代码,应用程序的内存增加是否有任何变化? – 2017-06-29 06:17:43

0

我一直运行到这一问题特别麻烦的图像上。接受的答案不适合我。

相反,我使用了流填充位:

using (FileStream fs = new FileStream(path, FileMode.Open)) 
{ 
    bitmap.BeginInit(); 
    bitmap.StreamSource = fs; 
    bitmap.CacheOption = BitmapCacheOption.OnLoad; 
    bitmap.EndInit(); 
} 

这导致要释放的文件句柄。