0

I'm having this really weird problem and wanted to see if you guys could give me some advice here. I want to load an image into an image control from a specific file URI, but I want to have the option to delete the file from the file system as well. The problem is that I keep getting this error:

"The process cannot access the file 'c:\38.gif' because it is being used by another process."

Here is my code (VB.NET but C# solutions will be helpful as well!):

'to load the image

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

And then if the user clicks a button, I want to delete that particular file like this:

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

Anyone have any idea how I can load the image yet still be able to delete the source file??

Many thanks in advance!

deskplace
  • 36
  • 3
  • 1
    @TrevorSullivan that solution is for WM6, not WPF. I'll take another look at it though just in case it sparks any ideas. Thanks ;) – deskplace Jan 22 '14 at 05:08

2 Answers2

1

Just add

bitmap1.CacheOption = BitmapCacheOption.OnLoad;

after BeginInit()

gomi42
  • 2,449
  • 1
  • 14
  • 9
  • I tried this before, but it doesn't let me access the GIF animation. I should have included that requirement in my question, sorry! – deskplace Jan 22 '14 at 15:39
0

The link that Trevor Sullivan included in his comment led me to the answer. Below is the code for anyone dealing with a similar problem.

    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
deskplace
  • 36
  • 3