2014-01-22 56 views
0

我有這個很奇怪的問題,想看看你們是否可以給我一些建議。我想從一個特定的文件URI將圖像加載到圖像控件中,但是我想要從文件系統中刪除文件。問題是我不斷收到此錯誤:如何從文件系統中加載圖像(到圖像控件中),然後從文件系統中刪除它

「該進程無法訪問文件'c:\ 38.gif',因爲它正在被另一個進程使用。」

這裏是我的代碼(VB.NET,但C#的解決方案將是有益的!):

「加載圖像

Dim bitmap1 as New BitmapImage 
bitmap1.BeginInit() 
bitmap1.UriSource = New Uri("c:\38.gif", UriKind.Absolute) 
bitmap1.EndInit() 
Image1.Source = bitmap1.Clone 

然後如果用戶點擊一個按鈕,我想刪除像這樣的特定文件:

Image1.Source = Nothing 
File.Delete("c:\38.gif") 

任何人有任何想法如何我可以加載圖像,但仍然能夠刪除源文件?

非常感謝提前!

+1

@TrevorSullivan該解決方案是爲WM6,而不是WPF。我會再看看它,但以防萬一它引發任何想法。謝謝;) – deskplace

回答

1

只需添加

bitmap1.CacheOption = BitmapCacheOption.OnLoad;

BeginInit在後

()

+0

我以前試過,但它不讓我訪問GIF動畫。我應該在我的問題中包含這個要求,對不起! – deskplace

0

特雷弗沙利文在他的評論使我的答案的鏈接。以下是處理類似問題的任何人的代碼。

bitmap1 = New BitmapImage 

    Using photoStream As System.IO.FileStream = New System.IO.FileStream(currentfile, FileMode.Open, FileAccess.Read) 
     bitmap1.BeginInit() 
     Using reader As New BinaryReader(photoStream) 
      'copy the content of the file into a memory stream 
      Dim memoryStream = New MemoryStream(reader.ReadBytes(CInt(photoStream.Length))) 
      'make a new Bitmap object the owner of the MemoryStream 
      bitmap1.StreamSource = memoryStream 
     End Using 
     bitmap1.EndInit() 
     leimage.Source = bitmap1 
     photoStream.Dispose() 

    End Using 
相關問題