2

I am currently trying to display an image in a WPF dialog, which can be replaced by the user at anytime, causing this imagefile to be overwritten. My problem is: while the image is displayed in my dialog, the image seems to be locked by WPF, so when I try to replace it, it cannot be accessed.

How can I force WPF to release the image when I upload a new one? Here is part of my Code:

XAML:

<Image Margin="6" VerticalAlignment="Center" HorizontalAlignment="Center" Source="{Binding ImageFileFullPath}"/>

C#:

string sourceFile = openFileDialog.FileName;
string destinationFile = Path.Combine(Environment.ExpandEnvironmentVariables(Constants.ImagePathConstant), destinationFileWithoutPath);
mViewModel.ImageFileFullPath = ""; //temporarily set the image file to another entry hoping WPF releases my image
try
{
    File.Copy(sourceFile, destinationFile, true); //fails the second time with exception 
}
catch (Exception)
{                   
    throw;
}

Even trying to set the image to an empty path temporarily does not fix the problem.

Exception I get: An unhandled exception of type 'System.IO.IOException' occurred in PresentationFramework.dll

Erik
  • 2,316
  • 9
  • 36
  • 58

1 Answers1

0

I had a situation where I needed the user to select an image to display and then move the location of the image. What I quickly found was while I was bound to the image I was holding a file lock on it that prevented me from moving it. On a BitmapImage there is a CacheOption that allows you to cache OnLoad. Unfortunately I couldn’t set this on the bindings for the Image so to get around it I had to use a converter on the Source :

public class ImageCacheConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {

        var path = (string)value;
        // load the image, specify CacheOption so the file is not locked
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriSource = new Uri(path);
        image.EndInit();

        return image;

    }

    public object ConvertBack(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException("Not implemented.");
    }
} 

XAML:

<Image Source="{Binding Path=SmallThumbnailImageLocation, Converter=StaticResource imagePathConverter}}"/>
Matti9811
  • 42
  • 2