2014-09-11 21 views
0

我有一個WPF應用程序,它使用本地存儲在機器中的一些圖像文件。作爲一個清理過程,我必須在應用程序關閉時刪除所有圖像。保存本地存儲的圖像文件並不允許刪除的應用程序進程

對於清除,我使用IDisposable和調用方法來刪除圖像文件,但方法拋出異常,該文件無法刪除,因爲它被進程使用。

在實現析構函數並從它調用清理方法工作正常,它清理所有文件,但我不允許使用它。

需要幫助才能從我可以調用清理的位置獲取該特定位置。

僅供參考,下面的代碼用於通過實現IDisposable來刪除圖像。

private void Dispose(bool disposing) 
     { 
      if (!this.disposed) 
      { 
       if (disposing) 
       { 
        this.CleanUp(); 
        this.disposed = true; 
       } 
      } 
     } 

void CleanUpModule(object sender, EventArgs e) 
     { 

      var folderPath = 
       Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Somelocation\\IconImages\\"); 

      if (Directory.Exists(folderPath) == false) 
      { 
       return; 
      } 

      // Clean all the temporary files. 
      foreach (var file in Directory.GetFiles(folderPath)) 
      { 
       File.Delete(file); 
      } 

     } 
+1

我想這也是很重要的,你是如何使用的圖片..還有一些版本的代碼應該發生 – 2014-09-11 07:33:20

+0

@kishoreVM同意,使用'新的BitmapImage(URI)」是導致該問題的一種方法加載圖像。 – kennyzx 2014-09-11 07:42:16

+1

@ kennyzx設置BitmapCacheOption.OnLoad也適用於從本地文件Uri加載圖像。儘管明確使用(和關閉)流可能是「更安全」的方式。 – Clemens 2014-09-11 08:10:20

回答

2

一種解決方案是將圖像讀取到臨時流並在讀取圖像後關閉流。您可以快樂地刪除原始文件,因爲它們實際上不再被該進程佔用。

var bmpImg = new BitmapImage(); 
using (FileStream fs = new FileStream(@"Images\1.png", FileMode.Open, FileAccess.Read)) 
{ 
    // BitmapImage.UriSource/StreamSource must be in a BeginInit/EndInit block. 
    bmpImg.BeginInit(); 
    bmpImg.CacheOption = BitmapCacheOption.OnLoad; 
    bmpImg.StreamSource = fs; 
    bmpImg.EndInit(); 
} 
imageControl.Source = bmpImg; 
相關問題