2013-05-13 124 views
0

我有以下代碼:WPF不能刪除文件

imgScreenshot.Source = new BitmapImage(new Uri(ShellFolder.DocumentsFolder() + System.IO.Path.DirectorySeparatorChar + screenshot.Filename)); 
File.Delete(ShellFolder.DocumentsFolder() + System.IO.Path.DirectorySeparatorChar + screenshot.Filename); 

我得到一個錯誤:

{"The process cannot access the file 'C:\Users\rover\Documents\MagicScreenshot\vEhWg3Ra20M.jpg' because it is being used by another process."}

我想過處置BitmapImage的,但這個類沒有實現這個接口。如何正確編寫此代碼?

+0

嘗試把代碼來刪除文件中的事件處理程序['DownloadCompleted'(http://msdn.microsoft.com/en-us/library/system。 windows.media.imaging.bitmapsource.downloadcompleted.aspx)事件。 – 2013-05-13 11:49:38

回答

2

嘗試:

 BitmapImage bi = new BitmapImage(); 
     bi.BeginInit(); 
     bi.UriSource = new Uri(ShellFolder.DocumentsFolder() + System.IO.Path.DirectorySeparatorChar + screenshot.Filename); 
     bi.CacheOption = BitmapCacheOption.OnLoad; 
     bi.EndInit(); 
     imgScreenshot.Source = bi; 
     File.Delete(ShellFolder.DocumentsFolder() + System.IO.Path.DirectorySeparatorChar + screenshot.Filename);