WPF BitmapImage 图片资源无法删除,文件正在被另一个进程使用

前两天由于项目需要,需要做一个基于wpf的图片展示器,基本都已经ok

但是在删除图片的时候,出现了大麻烦,搞了N久,终于在朋友的帮助下,解决了这个问题。

wpf图片展示器基于

http://www.cnblogs.com/know/archive/2011/11/25/2263723.html

这位仁兄的

在点击delete按钮时,项目报异常:“...无法删除,文件正在被另一个进程使用”,

以流的形式绑定listbox就行。不能使用

pictureBox.clear();

查了一些资料,这个异常的根本原因是因为BitmapImage没有Dispose()方法,系统虽然删除了image,但是图片文件仍然被当前进程占用着。


 

于是,将源代码修改如下解决(不再给BitmapImage直赋filePath,而是先根据filePath读取图片的二进制格式,赋给BitmapImage的Source,这样就可以在图片读取完毕后关闭流)。

解决方案:

       // Construct the ListBoxItem with an Image as content:
                    ListBoxItem item = new ListBoxItem();
                    item.Padding = new Thickness(3, 8, 3, 8);
                    item.MouseDoubleClick += delegate { ShowPhoto(false); };
                    TransformGroup tg = new TransformGroup();
                    tg.Children.Add(st);
                    tg.Children.Add(new RotateTransform());
                    item.LayoutTransform = tg;
                    item.Tag = s;
                    Stream stream = File.OpenRead(s);
                    Stream fs = FileStream.Synchronized(stream);
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = fs;
                    bitmap.EndInit();
                    BitmapImage bb = bitmap.Clone();
                    Image image = new Image();
                    image.Height = 35;
                    // If the image contains a thumbnail, use that instead of the entire image:
                    //Uri uri = new Uri(s);
                    //BitmapDecoder bd = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    //if (bd.Frames[0].Thumbnail != null)
                    //    image.Source = bd.Frames[0].Thumbnail;
                    //else
                    image.Source = bb;
                    stream.Dispose();
                    fs.Dispose();
                    // Construct a ToolTip for the item:
                    Image toolImage = new Image();
                    //toolImage.Source = bd.Frames[0].Thumbnail;

                    TextBlock textBlock1 = new TextBlock();
                    textBlock1.Text = System.IO.Path.GetFileName(s);
                    TextBlock textBlock2 = new TextBlock();
                    textBlock2.Text = photo.DateTime.ToString();

                    StackPanel sp = new StackPanel();
                    sp.Children.Add(toolImage);
                    sp.Children.Add(textBlock1);
                    sp.Children.Add(textBlock2);

                    item.ToolTip = sp;
                    item.Content = image;
                    pictureBox.Items.Add(item);

原文地址:https://www.cnblogs.com/dodui/p/2420132.html