Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot delete file used by some other process

I am displaying some image in my wpf app using following code:

 <Image Source="{Binding Path=TemplateImagePath, Mode=TwoWay}"  Grid.Row="3" Grid.Column="2"  Width="400" Height="200"/>

and setting it's binding property inside code behind's constructor by navigating through some directory, below is the code:

DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
            if (Dir.Exists)
            {
                if (Dir.GetFiles().Count() > 0)
                {
                    foreach (FileInfo item in Dir.GetFiles())
                    {
                        TemplateImagePath = item.FullName;
                    }
                }
            }

but if user upload some other image then I need to delete this old image which is I am doing in the following way and setting image binding to null:

DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
                if (Dir.Exists)
                {
                    if (Dir.GetFiles().Count() > 0)
                    {
                        foreach (FileInfo item in Dir.GetFiles())
                        {
                            TemplateImagePath= null;
                            File.Delete(item.FullName);
                        }
                    }
                }

But Iam getting exception that Cannot delete file used by some other process. How can I delete it?

like image 385
SST Avatar asked Jan 16 '23 09:01

SST


1 Answers

In order to be able to delete the image while it is displayed in an ImageControl, you have to create a new BitmapImage or BitmapFrame object that has BitmapCacheOption.OnLoad set. The bitmap will then be loaded from file immediately and the file is not locked afterwards.

Change your property from string TemplateImagePath to ImageSource TemplateImage and bind like this:

<Image Source="{Binding TemplateImage}"/>

The set the TemplateImage property like this:

BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(item.FullName);
image.EndInit();
TemplateImage = image;

or this:

TemplateImage = BitmapFrame.Create(
    new Uri(item.FullName),
    BitmapCreateOptions.None,
    BitmapCacheOption.OnLoad);

If you want to keep binding to your TemplateImagePath property you may instead use a binding converter that converts the string to an ImageSource as shown above.

like image 63
Clemens Avatar answered Jan 30 '23 07:01

Clemens