views:

289

answers:

1

In a Silverlight app, I save a Bitmap like this:

public static void SaveBitmapImageToIsolatedStorageFile(OpenReadCompletedEventArgs e, string fileName)
{
    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
        {
            Int64 imgLen = (Int64)e.Result.Length;
            byte[] b = new byte[imgLen];
            e.Result.Read(b, 0, b.Length);
            isfs.Write(b, 0, b.Length);
            isfs.Flush();
            isfs.Close();
            isf.Dispose();
        }
    }
}

and read it back out like this:

public static BitmapImage LoadBitmapImageFromIsolatedStorageFile(string fileName)
{
    string text = String.Empty;

    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (!isf.FileExists(fileName))
            return null;

        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isoStream = isoStore.OpenFile(fileName, FileMode.Open))
            {
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(isoStream);
                return bitmapImage; // "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))"
            }
        }
    }
}

but this always gives me a "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" error.

I've seen this error before when I tried to read a png file off a server which was actually a text file, so I assume the Bitmap is not being saved correctly, I got the code here.

Can anyone see how the BitmapImage is not being saved correctly? Or why it would be giving me this error?

Update:

When the BitmapImage is created, I see that the array of bytes that gets written is 1876 bytes long and they are all 0. Why would that be?

+1  A: 

I got it to work but am unclear exactly why. I was calling SaveBitmapImageToIsolatedStorageFile(...) after this code:

BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(e.Result);
Image image = new Image();
image.Source = bitmapImage;

If I call it before that code, then it works.

Apparently SetSource() zeroes out the bytes in e.Result but keeps the length?

Edward Tanguay