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

来源:互联网 发布:淘宝的导购网站 编辑:程序博客网 时间:2024/06/07 16:17

代码如下所示,项目本意是想在窗体加载时显示一张图片,然后点击按钮,删除该图片。

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

xaml 代码: 

     <Grid x:Name="LayoutRoot"> 

        <Grid.RowDefinitions> 

            <RowDefinition/> 

            <RowDefinition/> 

        </Grid.RowDefinitions> 

        <Button  Grid.Row="1" Click="Button_Click" Content="Delete" Margin="212,16,183,58" /> 

    </Grid> 

C#代码 

    public partial class MainWindow : Window 

    { 

        string filePath = @"D:/11.图片/6.jpg"; 

        Image image; 

        BitmapImage bitmapImage; 

        public MainWindow() 

        { 

            InitializeComponent(); 

            image=new Image(); 

            bitmapImage = new BitmapImage(new Uri(filePath, UriKind.Absolute)); 

            image.Source=bitmapImage; 

            this.LayoutRoot.Children.Add(image); 

        } 

        private void Button_Click(object sender, RoutedEventArgs e) 

        { 

            this.LayoutRoot.Children.Remove(image); 

            File.Delete(filePath); //这里出现异常 

        } 

    }

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

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

解决后的代码如下:

public partial class MainWindow : Window 

    { 

        string filePath = @"D:/11.图片/6.jpg"; 

  

        BitmapImage bitmapImage; 

        Image image; 

  

        public MainWindow() 

        { 

            InitializeComponent(); 

            this.InitImage();            

        } 

  

        private void InitImage() 

        { 

            using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open))) 

            { 

                FileInfo fi = new FileInfo(filePath); 

                byte[] bytes = reader.ReadBytes((int)fi.Length); 

                reader.Close(); 

  

                image = new Image(); 

                bitmapImage = new BitmapImage(); 

                bitmapImage.BeginInit(); 

                bitmapImage.StreamSource = new MemoryStream(bytes); 

                bitmapImage.EndInit(); 

                image.Source = bitmapImage; 

                bitmapImage.CacheOption = BitmapCacheOption.OnLoad; 

                this.LayoutRoot.Children.Add(image); 

            } 

        } 

文章来自学IT网:http://www.xueit.com/html/2011-02/111-801833600201122291256640.html

原创粉丝点击