0

The following code is used in a loop to load images into a XAML Listbox:

Dim image As New Image
Dim uri As New Uri(filePathAndName)
image.Source = New BitmapImage(uri)

Another post comments in the answer that the BitmapImage class hangs on to the file handle which is what I observe.

Various other posts gave examples of how to load the images without getting a file lock. This is the one I used:

Dim image As New Image
Using stream = New FileStream(filePathAndName, FileMode.Open)
  Dim bitmapImage As New BitmapImage
  bitmapImage.BeginInit()
  bitmapImage.CacheOption = BitmapCacheOption.OnLoad
  bitmapImage.StreamSource = stream
  bitmapImage.EndInit()
  image.Source = bitmapImage
End Using

The second coding loads the images without file locks, but it is much slower.

Are there no ways to force the file lock off using bitmapImage in the first set of code?

Community
  • 1
  • 1
Alan
  • 1,587
  • 3
  • 23
  • 43
  • You *may* be able to use [`BitmapFrame.Create`](https://msdn.microsoft.com/en-us/library/ms615996(v=vs.110).aspx). The result can be used by anything that accepts a `BitmapSource`. Make *sure* you pay special attention to the Remarks section. It has important information about how / when you can close the stream. – Bradley Uffner Feb 09 '17 at 19:29
  • Similar to BitmapImage you would have to specify `BitmapCacheOption.OnLoad` (in another [`BitmapFrame.Create`](https://msdn.microsoft.com/en-us/library/ms615998(v=vs.110).aspx) overload) to force immediate loading of the BitmapSource. I doubt that it would be faster than using a BitmapImage. – Clemens Feb 09 '17 at 20:16
  • Is it correct for me to understand the .Create suggestion is solely in response to the speed issue and not related to getting the file lock released? – Alan Feb 10 '17 at 00:51
  • Both. It was just another option I found, I don't know if it will be faster or not. It *might* be faster, since it takes the stream in the constructor, instead of instantiating the image and then stuffing data in to it in different steps. If you pass the correct arguments (as mentioned in the "remarks" section) you can also get it to not lock the stream. – Bradley Uffner Feb 10 '17 at 02:05
  • I'll give it a go and report back later what I find. Thx. – Alan Feb 10 '17 at 18:03

0 Answers0