2014-01-22 23 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 
相关问题