0

I am trying to show an image in WPF. I use this:

            Stream fs = File.Open(path, FileMode.Open);

            BitmapImage bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = fs;
            bmp.EndInit();
            img.Source = bmp;
            fs.Close();

This does not work with or without closing the stream. What does work:

            BitmapImage bmp = new BitmapImage(new Uri(path));
            img.Source = bmp;

I would use the second method except for the fact that I need to close the stream. What is wrong with this?

derp_in_mouth
  • 2,003
  • 4
  • 15
  • 17

1 Answers1

1

To anyone looking for this in the future: I fixed this by adding the following line before setting StreamSource: bmp.CacheOption = BitmapCacheOption.OnLoad;

Full Code:

            BitmapImage bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.CacheOption = BitmapCacheOption.OnLoad;
            bmp.StreamSource = fs;
            bmp.EndInit();
            img.Source = bmp;
derp_in_mouth
  • 2,003
  • 4
  • 15
  • 17