Question

I wrote a WPF Application that opens a PowerPoint presentation and save the slides as images to be displayed in a PictureBox. The PictureBox is bounded to ImageBitmap property.

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

When the application is closed, I would like to delete all the image files created, but instead I got an error: "“The process cannot access the file because it is being used by another process”. I have determined (using ProcessExplorer) that the files were being used only by my application.

I read some suggestions that using the code below will allow the image file (located in ImagePath) to be deleted, but I think this will break MVVM since the viewModel now knows about the 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;
            }
        }
Était-ce utile?

La solution

You may set the BitmapCacheOption.OnLoad option during initialization of the BitmapImage. This lets WPF close the image file right after loading the image.

var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(ImagePath);
bitmap.EndInit();
ImageBitmap = bitmap;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top