0

I have a WPF application which uses some image files stored locally in machine. As a cleanup process I have to delete all images when application closes.

For clearing i am using IDisposable and calling method to delete the Image files but method throws exception that file cannot be deleted as it is used by process.

On implementing destructor and calling cleanup method from it works fine and it cleans all files, but I am not allowed to use it.

Need help to get that particular location from where I can call cleanup.

just for reference, below code I am using for deleting images by implementing IDisposable.

private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                   this.CleanUp();
                    this.disposed = true;
                }
            }
        }

void CleanUpModule(object sender, EventArgs e)
        {

            var folderPath =
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Somelocation\\IconImages\\");

            if (Directory.Exists(folderPath) == false)
            {
                return;
            }

            // Clean all the temporary files.
            foreach (var file in Directory.GetFiles(folderPath))
            {
                File.Delete(file);
            }

        }
Amit
  • 33
  • 2
  • 11
  • 1
    I think it also matters how you are using the Images .. there some release code should happen – kishore V M Sep 11 '14 at 07:33
  • @kishoreVM Agree, loading image using `new BitmapImage(Uri)" is one way that causes the problem. – kennyzx Sep 11 '14 at 07:42
  • 1
    @kennyzx Setting BitmapCacheOption.OnLoad also works when you load the image from a local file Uri. Although explicitly using (and closing) a stream is probably the "safer" way. +1. – Clemens Sep 11 '14 at 08:10

1 Answers1

2

One solution is to read the images to a temporary stream and close the stream after the image is read. You can delete the original files happily since they are actually not occpied by the process anymore.

var bmpImg = new BitmapImage();
using (FileStream fs = new FileStream(@"Images\1.png", FileMode.Open, FileAccess.Read))
{
    // BitmapImage.UriSource/StreamSource must be in a BeginInit/EndInit block.
    bmpImg.BeginInit();
    bmpImg.CacheOption = BitmapCacheOption.OnLoad;
    bmpImg.StreamSource = fs;
    bmpImg.EndInit();
}
imageControl.Source = bmpImg;
kennyzx
  • 12,845
  • 6
  • 39
  • 83