删除由WPF应用程序中的Interop Powerpoint创建的映像

时间:2014-04-28 07:16:02

标签: wpf interop powerpoint

我写了一个WPF应用程序,它打开PowerPoint演示文稿并将幻灯片保存为要在PictureBox中显示的图像。 PictureBox与ImageBitmap属性绑定。

        PowerPoint.Application app = new PowerPoint.Application();
        PowerPoint.Presentations pres = app.Presentations;
        p = pres.Open(FileName, ofalse, ofalse, otrue);
        p.Slides[0].Export(ImagePath, "png", 640, 480);         
        ImageBitmap = new BitmapImage(new Uri(ImagePath));

当应用程序关闭时,我想删除所有创建的图像文件,但我得到一个错误:“”进程无法访问该文件,因为它正被另一个进程使用“。 我已经确定(使用ProcessExplorer)文件仅由我的应用程序使用。

我读到一些建议,使用下面的代码将允许删除图像文件(位于ImagePath中),但我认为这将打破MVVM,因为viewModel现在知道View。

        Image im = GetCopyImage(@"D:\Temp\AAAA.jpg");
        myPictureBox.Image = im;
        File.Delete(@"D:\Temp\AAAA.jpg");
        }

        private Image GetCopyImage(string path)
        {
        using (Image im = Image.FromFile(path))
            {
            Bitmap bm = new Bitmap(im);
            return bm;
            }
        }

1 个答案:

答案 0 :(得分:0)

您可以在初始化BitmapImage期间设置BitmapCacheOption.OnLoad选项。这样,WPF可以在加载图像后立即关闭图像文件。

var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(ImagePath);
bitmap.EndInit();
ImageBitmap = bitmap;