2015-09-28 21 views
0

我讀過可能所有關於這個帖子。似乎無法找到問題。 這是我收集WPF無法從代碼中刪除圖像。 IOException

private ObservableCollection<BitmapImage> _imageList = new ObservableCollection<BitmapImage>(); 

這也是我如何載入我的圖片

foreach (string filepath in temp) //populate image collection 
{ 
    BitmapImage tempImg = new BitmapImage(); 
    tempImg.BeginInit(); 
    tempImg.CacheOption = BitmapCacheOption.OnLoad; 
    tempImg.UriSource = new Uri(filepath); 
    tempImg.EndInit(); 
    _imageList.Add(tempImg); 
} 

唯一的例外發生在線路當我嘗試刪除該文件正在使用中。

if (File.Exists(_imageList[SelectedItem].UriSource.AbsolutePath.ToString())) 
{ 
    int temp = SelectedItem; 
    //_imageList.RemoveAt(temp); 
    Console.WriteLine(_imageList[temp].UriSource.AbsolutePath.ToString()); 
    File.Delete(_imageList[temp].UriSource.AbsolutePath.ToString()); 
} 

除外:

類型「System.IO.IOException」的一個例外發生在mscorlib.dll但在用戶代碼中沒有處理。

附加信息:進程無法訪問文件'e:\ pix \ img.jpg',因爲它正在被另一個進程使用。

有人可以重新打開嗎?我想出了問題,這不是這個代碼,它是在視圖的部分,我想發佈一個答案。

+0

它可能不會解決你的問題,但你應該添加tempImg.Freeze(); tempImg.EndInit();以避免內存泄漏。 –

+0

謝謝你,我已經這樣做了,沒有幫助我更新代碼的io異常 – Akos

回答

0

但是,這個例外是什麼意思?它在哪一行代碼被解僱? 我敢打賭,你的BitmapImage保存文件,這就是爲什麼你不能刪除它,你應該首先處置它。

有時候WPF只是保存文件,在這種情況下它的好,只是字節從文件存儲和息事寧人,這樣的:

private BitmapImage loadImage(string imgPath) 
    { 
     BitmapImage myRetVal = null; 
     if (imgPath != null) 
     { 
      BitmapImage img = new BitmapImage(); 
      using (FileStream stream = File.OpenRead(imgPath)) 
      { 
       img.BeginInit(); 
       img.CacheOption = BitmapCacheOption.OnLoad; 
       img.StreamSource = stream; 
       img.EndInit(); 
      } 
      myRetVal = image; 
     } 
     return myRetVal; 
    } 
+0

。 – Akos

+0

檢查上面的替代方法 –

0

您從列表中刪除temp'th項目,之後立即重新使用它。鑑於事實,列表中有足夠的項目,錯誤的文件將被刪除。否則你會得到一個IndexOutOfRangeException。

此外,UriSource.AbsolutePath是一個字符串,那麼使用ToString()就沒有意義了。

從發佈的代碼中無法看到,爲什麼該文件可能正在使用中。請檢查另一個應用程序是否保留該文件(或其他地方)。

+0

這是真的,但仍然,即使沒有這段代碼,我仍然得到相同的錯誤,IO異常。我將再次編輯它,以澄清 – Akos

+0

沒有其他應用程序使用該文件,只要我關閉該應用程序,我可以從勝利中刪除它。資源管理器,在關閉之前,它也給我一個使用中的文件錯誤。 – Akos

+0

您的代碼中是否有任何其他部分訪問這些文件? – JeffRSon