Marcel Grüger Marcel Grüger - 15 days ago 6
C# Question

BitmapCacheOption.OnLoad show only white Image

I use the following code to load an image (in multiple windows at once):

BitmapImage tempBitmapImage = new BitmapImage();
tempBitmapImage.BeginInit();
tempBitmapImage.UriSource = new Uri(_fileList[_fileCounter].FileName);
tempBitmapImage.CacheOption = BitmapCacheOption.Default; //.OnLoad;
tempBitmapImage.EndInit();
tempImage.Source = tempBitmapImage;


If I use the Default option the image loads and is shown but the app can crash when multiple windows try to load the file and the file is then removed by the updater that is running in the background. If I use the OnLoad-option the file should be completly in the memory when I change the image from one image to another one. But when I do so, there is only a white image, no error messages, no colors, only a white screen.

Someone an idea what that could be?

Answer

You could directly load the BitmapImage from a FileStream:

var tempBitmapImage = new BitmapImage();

using (var stream = new FileStream(
    _fileList[_fileCounter].FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
    tempBitmapImage.BeginInit();
    tempBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    tempBitmapImage.StreamSource = stream;
    tempBitmapImage.EndInit();
}

tempImage.Source = tempBitmapImage;