WPF如何删除已经打开的图片文件
在WPF中,你也许会碰到这种情况,图片在界面打开,想用File.Delate()删除却无法删除。
比如:
XAML:
<Window x:Class="WPF_Testing_Application.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Height="100" Name="stackPanel1" Width="200" />
</Window>
Code:
public Window1()
{
InitializeComponent();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Autumn Leaves - Copy.jpg");
bi.EndInit();
Image image1 = new Image();
image1.Source = bi;
stackPanel1.Children.Add(image1);
stackPanel1.MouseLeftButtonDown += delegate { DeleteImage(); };
}
private void DeleteImage()
{
stackPanel1.Children.RemoveAt(0);
File.Delete(@"C:\Users\Public\Pictures\Sample Pictures\Autumn Leaves - Copy.jpg");
}
这样会出现文件被占用,无法删除的异常。
解决办法:www.2cto.com
把代码改成:
public Window1()
{
InitializeComponent();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad; //增加这一行
bi.UriSource = new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Autumn Leaves - Copy.jpg");
bi.EndInit();
Image image1 = new Image();
image1.Source = bi;
stackPanel1.Children.Add(image1);
stackPanel1.MouseLeftButtonDown += delegate { DeleteImage(); };
}
就可以了。
如果你用ObservableCollection<BitmapImage>作为datasouce,
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri("Blue hills.jpg", UriKind.Relative);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
用以下方式删除就可以了:
BitmapImage img = (BitmapImage)listPictures.SelectedItem;
File.Delete(img.UriSource.ToString());
摘自 soft2buy
相关新闻>>
- 发表评论
-
- 最新评论 进入详细评论页>>
今日头条
更多>>您可能感兴趣的文章
- Asp.net MVC源码分析--Model Validation(Client端)实现(2)
- 谈.Net委托与线程——创建无阻塞的异步调用(一
- 教你如何来恢复一个丢失的数据文件
- Pro ASP.NET MVC 3 Framework学习笔记之九
- 微软ASP.NET站点部署指南(11):部署SQL Server数据
- asp.net 六大内置对象(2)
- winform下通过webclient使用非流方式上传(post)数据和
- asp.net js模拟Button点击事件
- ASP.NET数据格式的Format--DataFormatString
- MVC中一个表单实现多个提交按钮(一个action搞定