Release handle on file. ImageSource from BitmapImage
Asked Answered
D

2

28

How can I release the handle on this file?

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

Solution


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;
}
Droll answered 25/4, 2012 at 16:6 Comment(2)
what are these 3 lines : img.Source = imageSrc; //Do Work imageSrc = null; img.Source = null;Antipathetic
@MonsterMMORPG don't worry about them... bitmap.CacheOption = BitmapCacheOption.OnLoad; is the magic part.Droll
P
37

Found the answer on MSDN Forum.

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

And when you get an ImageSource using the method above, source file will be immediately closed.

see MSDN social forum

Performative answered 25/4, 2012 at 16:19 Comment(1)
if I use this code is there any changes of Memory increase of the application?Flavourful
B
1

I kept running into issues with this on a particularly troubling image. The accepted answer did not work for me.

Instead, I used a stream to populate the bitmap:

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

This caused the file handle to be released.

Boob answered 7/3, 2017 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.