wpf - 无法删除其他进程使用的文件

标签 wpf c#-4.0 file-io ioexception

我正在使用以下代码在我的 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 中显示图像时删除它,您必须创建一个新的 BitmapImageBitmapFrame具有 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/

相关文章:

c# - WPF 上的嵌套网格问题

java - 将文本文件插入二维数组

Java 文本文件递归

c# - 更好的逻辑来检查财政年度日期

c# - 从 csv 文件读取并在 .net 中处理它

javascript - 如何在 Firefox 和 Chrome 中通过网站上的链接打开文件夹?

c# - WPF Glyph Run 错误地渲染度数符号

wpf - 在处理时更新 WPF UI - 异步等待的最佳使用

c# - 如何滚动到 wpf mvvm 中数据网格中新添加的行

c# - 具有动态参数的表达式树