2012-10-09 46 views
2

我使用下面的代码在我的WPF应用程序显示某些图像使用的文件:无法删除由其他进程

<Image Source="{Binding Path=TemplateImagePath, Mode=TwoWay}" Grid.Row="3" Grid.Column="2" Width="400" Height="200"/> 

,并设置它通过一些目录导航结合内部的代码背后的constructor属性,下面是代码:

DirectoryInfo Dir = new DirectoryInfo(@"D:/Template"); 
      if (Dir.Exists) 
      { 
       if (Dir.GetFiles().Count() > 0) 
       { 
        foreach (FileInfo item in Dir.GetFiles()) 
        { 
         TemplateImagePath = item.FullName; 
        } 
       } 
      } 

但如果用户上传一些其他的图像,然后我需要删除这是我在下面的方式做,并设置图像结合为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); 
         } 
        } 
       } 

但Iam得到异常,无法删除某些其他进程使用的文件。 我该如何删除它?

+0

您是否尝试过不使用双向绑定?可以工作的另一个解决方案是不直接设置路径,而是从路径创建一个BitmapImage并绑定到该位图图像。 – Akku

+0

该怎么做。我是新手在WPF.any代码示例 – SST

+0

对不起,没时间,请使用Google。 – Akku

回答

6

为了能够在图像显示在ImageControl中时删除图像,必须创建一个新的BitmapImageBitmapFrame对象,该对象具有BitmapCacheOption.OnLoad集。位图将立即从文件加载,然后文件不会被锁定。

string TemplateImagePath您的属性更改为ImageSource TemplateImage并结合这样的:

<Image Source="{Binding TemplateImage}"/> 

的设置TemplateImage属性是这样的:

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); 

如果您想保留绑定到您的TemplateImagePath属性,您可以改为使用binding converter将字符串转换为ImageSource,如上所示。

+0

非常感谢..这工作真棒。 – SST

+2

另外我需要添加'System.GC.Collect(); System.GC.WaitForPendingFinalizers();”在删除该行之前的那个文件之前:File.Delete(item.FullName) – SST

+0

在此上花费时间,但添加'GC.Collect();'和'GC.WaitForPendingFinalizers();'删除之前解决了我的问题。谢谢@SST – Sandwich