释放文件上的句柄.图像来源来自 BitmapImage

本文关键字:BitmapImage 图像 句柄 文件 释放 | 更新日期: 2023-09-27 18:32:09

如何释放此文件的句柄?

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

释放文件上的句柄.图像来源来自 BitmapImage

在 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;
}

当您使用上述方法获取图像源时,源文件 将立即关闭。

请参阅 MSDN 社交论坛

我一直在一个特别令人不安的图像上遇到这个问题。接受的答案对我不起作用。

相反,我使用流来填充位图:

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

这导致释放文件句柄。