我正在使用以下代码在我的 wpf 应用程序中显示一些图像:
<Image Source="{Binding Path=TemplateImagePath, Mode=TwoWay}" Grid.Row="3" Grid.Column="2" Width="400" Height="200"/>
并通过浏览某个目录在构造函数后面的代码中设置它的绑定(bind)属性,下面是代码:
DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
if (Dir.Exists)
{
if (Dir.GetFiles().Count() > 0)
{
foreach (FileInfo item in Dir.GetFiles())
{
TemplateImagePath = item.FullName;
}
}
}
但是如果用户上传了一些其他图像,那么我需要删除这个旧图像,我正在按照以下方式进行操作,并将图像绑定(bind)设置为 null:
DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
if (Dir.Exists)
{
if (Dir.GetFiles().Count() > 0)
{
foreach (FileInfo item in Dir.GetFiles())
{
TemplateImagePath= null;
File.Delete(item.FullName);
}
}
}
但是我遇到了无法删除其他进程使用的文件的异常。
我怎样才能删除它?
最佳答案
为了能够在 ImageControl 中显示图像时删除它,您必须创建一个新的 BitmapImage或 BitmapFrame具有 BitmapCacheOption.OnLoad 的对象放。然后将立即从文件中加载位图,之后文件不会被锁定。
从 string TemplateImagePath
更改您的属性(property)至ImageSource TemplateImage
并像这样绑定(bind):
<Image Source="{Binding TemplateImage}"/>
设置
TemplateImage
像这样的属性(property):BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(item.FullName);
image.EndInit();
TemplateImage = image;
或这个:
TemplateImage = BitmapFrame.Create(
new Uri(item.FullName),
BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
如果您想继续绑定(bind)到您的
TemplateImagePath
您可以改为使用 binding converter 的属性如上所示,将字符串转换为 ImageSource。
关于wpf - 无法删除其他进程使用的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12799931/