Reputation: 2183
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?
Upvotes: 0
Views: 1391
Reputation: 2183
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;
Upvotes: 1