Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
335 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...