0

I think that my problem is related with closed Topic: How can I stop <Image Source="file path"/> process?. That topic is closed and the answer for it doesn't work for me.

My problem is fact, that I can't use File.Delete(path). It provides exception: "Additional information: The process cannot access the file 'C:\Images\2014_09\auto_12_53_55_beszelri_modified.jpg' because it is being used by another process".

I'm trying call this method in Window_OnClosed event. The idea is that I have to delete image's jpg file when I'm closing the window. Path of this file is the source of image control in WPF. I was trying set Image source to null before call that method but it doesn't work. How can I delete that file after or during close the window. When I tried close other file in that place it was succesfull.

This is the code of closed event. The CreateFileString method create the path.

private void ImageWindow_OnClosed(object sender, EventArgs e)
{
    var c = CarImage.Source.ToString();
    var a = CreateFileString(c);
    CarImage.Source = null;

    File.Delete(a);
}
Community
  • 1
  • 1
darson1991
  • 406
  • 6
  • 18

1 Answers1

1

For some annoying reason, the markup parser in WPF opens images and leaves the connection to the physical files open. I had a similar problem with allowing users to switch images. The way that I got around it was to use an IValueConverter to load the Image and set the BitmapImage.CacheOption to BitmapCacheOption.OnLoad. Try this:

public class FilePathToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.GetType() != typeof(string) || targetType != typeof(ImageSource)) return false;
        string filePath = value as string;
        if (filePath.IsNullOrEmpty() || !File.Exists(filePath)) return DependencyProperty.UnsetValue;
        BitmapImage image = new BitmapImage();
        try
        {
            using (FileStream stream = File.OpenRead(filePath))
            {
                image.BeginInit();
                image.StreamSource = stream;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.EndInit();
            }
        }
        catch { return DependencyProperty.UnsetValue; }
        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue;
    }
}

You can use it like this:

<Application.Resources>
    <Converters:FilePathToImageConverter x:Key="FilePathToImageConverter" />
</Application.Resources>

...

<Image Source="{Binding SomeObject.SomeImageFilePath, 
    Converter={StaticResource FilePathToImageConverter}, Mode=OneWay}" />
Sheridan
  • 68,826
  • 24
  • 143
  • 183