Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete image file used by XAML

Tags:

image

wpf

I'm trying to delete a Image file in WPF, but WPF locks the file.

    <Image Source="C:\person.gif" x:Name="PersonImage">
        <Image.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Delete..." x:Name="DeletePersonImageMenuItem" Click="DeletePersonImageMenuItem_Click"/>
            </ContextMenu>
        </Image.ContextMenu>
    </Image>

And the Click handler just looks like this:

    private void DeletePersonImageMenuItem_Click(object sender, RoutedEventArgs e)
    {
        System.IO.File.Delete(@"C:\person.gif");
    }

But, when I try to delete the file it is locked and cannot be removed.

Any tips on how to delete the file?

like image 357
Frode Lillerud Avatar asked Apr 02 '10 08:04

Frode Lillerud


4 Answers

My application Intuipic deals with this by using a custom converter that frees the image resource. See the code here.

like image 163
Kent Boogaart Avatar answered Oct 22 '22 17:10

Kent Boogaart


Using code behind, you can use the cache option BitmapCacheOption.OnLoad:

                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                bi.UriSource = new Uri(PathToImage);
                bi.EndInit();
                PersonImage.Source = bi;

Because I struggled to find it, I will add that if you want to replace the deleted image dynamically, you need to add the argument BitmapCreateOptions.IgnoreImageCache.

like image 41
Magellan Avatar answered Oct 22 '22 17:10

Magellan


First Remove it from the PersonImage control then delete the image. Hope that will help. As you have assigned to the control in source, and remove it without unassigning the control source.

PersonImage.Source = null; 
System.IO.File.Delete(@"C:\person.gif"); 

hope that will help.

like image 1
Asim Sajjad Avatar answered Oct 22 '22 16:10

Asim Sajjad


The most easiest way to do this will be, creating a temporary copy of your image file and using it as a source.. and then at end of your app, deleting all temp files..

static List<string> tmpFiles = new List<string>();

static string GetTempCopy(string src)
{
   string copy = Path.GetTempFileName();
   File.Copy(src, copy);
   tmpFiles.Add(copy);
   return copy;
}

static void DeleteAllTempFiles()
{
   foreach(string file in tmpFiles)
   {
      File.Delete(file);
   }
}

Image caching in WPF also can be configured to do this, but for some reason my various attempts failed and we get unexpected behaviour like not being able to delete or refresh the image etc, so we did this way.

like image 1
Akash Kava Avatar answered Oct 22 '22 15:10

Akash Kava