Transcendent
Transcendent

Reputation: 5755

Removing a file once it is loaded

I have written a class that dynamically generates a pie chart using the MS Excel interops. I'm saving this pie chart in the windows temp folder and I'm trying to remove the folder that contains this pie chart right after it is successfully loaded in an image control, so far :

    private void Tracker() {
        Pbar pbar = new Pbar();
        Thread t = new Thread(delegate() {
            Draw();
            Dispatcher.Invoke(delegate()
            {
                ImageSource IS = new BitmapImage(new Uri(System.IO.Path.GetTempPath() + "PieChartTemp\\Temp_files\\image002.png", UriKind.Absolute)); ImageBox.Source = IS;

            });
        });
        Thread Track = new Thread(delegate() {
            t.Start();
            Dispatcher.Invoke(() => pbar.Show());
            while (true) {
                if (!t.IsAlive) { Dispatcher.Invoke(() => pbar.Close());
                System.IO.Directory.Delete(System.IO.Path.GetTempPath() + "PieChartTemp", true);
                break;
                }
                Thread.Sleep(25);
            }
        });
        Track.Start();
    }

This method causes an error and it says the file is in use by a process (of course the process that loads it into the image control), my question is that how can I release this file to get it ready to be deleted ?

Upvotes: 0

Views: 45

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283723

Don't let BitmapImage do the file access. Instead,

  1. read the file into a MemoryStream
  2. close the file
  3. create the BitmapImage from the MemoryStream

Upvotes: 2

Related Questions