释放文件上的句柄。来自BitmapImage的ImageSource [英] Release handle on file. ImageSource from BitmapImage

查看:59
本文介绍了释放文件上的句柄。来自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.

查看MSDN社交论坛

这篇关于释放文件上的句柄。来自BitmapImage的ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆