Meloviz Meloviz - 3 months ago 15
C# Question

Displaying PNG Image from Isolated Storage

I've been working for a few days trying to figure out how to save and load images to and from isolated storage. Yesterday, I finally managed to fix whatever issue I was having with storing them, but now I need to add the image as the icon to a menu item, and I don't know what is wrong with my code:

var image = new System.Windows.Controls.Image();
using(var stream = new IsolatedStorageFileStream((string) (directory + file + ext),
FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly()))
{
image.Source = (BitmapSource) new PngBitmapDecoder(stream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOptions.Default).Frames[0];
}

Menu menu = new Menu();
MenuItem item = new MenuItem();
item.Header = file;
item.Icon = image;
menu.Items.Add(item);


The image comes up in the menu as the right size, but it's a blank image. The image file shows the image just fine when I preview it in Windows Photo Viewer.

I'm still pretty new to C# and WPF (only been working with it for 3 months), and I'm looking for a simple solution that doesn't really need to be elegant or generic; it just needs to work.

Answer

It figures that I would answer my own question half an hour after asking for help. Scoured the Web for days trying to figure it out, and it just falls in my lap. I just needed to instantiate my stream with the correct FileAccess:

I just replaced

using(var stream = new IsolatedStorageFileStream((string) (directory + file + ext), 
                   FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly()))

with

using(var stream = IsolatedStorageFile.GetUserStoreForAssembly().OpenFile(
                   (string) (directory + file + ext), FileMode.Open, FileAccess.Read))
Comments