加载后删除文件

时间:2014-01-14 00:52:01

标签: c#

我编写了一个使用MS Excel interops动态生成饼图的类。我将此饼图保存在Windows临时文件夹中,并且我试图在图像控件中成功加载后立即删除包含此饼图的文件夹,到目前为止:

    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();
    }

这个方法会导致错误并且它说文件正由进程使用(当然是将其加载到图像控件中的进程),我的问题是如何释放此文件以准备删除它?

1 个答案:

答案 0 :(得分:2)

不要让BitmapImage进行文件访问。取而代之的是,

  1. 将文件读入MemoryStream
  2. 关闭文件
  3. BitmapImage
  4. 创建MemoryStream