views:

24

answers:

1

Using C#/.NET for my application, I've got a series of classes in my main data model that represent "binary" (as opposed to text) content. I've got a inheritance setup like this:

alt text

Basically, the abstract class BinaryContent contains a MemoryStream that stores arbitrary binary data. That data is read from a file on disk. Each type of binary data I plan to store will be a derived type, such as ImageContent and FontContent. Those derived types will interpret the binary data in BinaryContent.Content. ImageContent for example, would create a BitmapImage (stored in an ImageSource) from the MemoryStream. FontContent would of course create a font from the BinaryContent.Content. I chose this way of doing things because I wanted to be able to basically store a copy of the content file (ie an image) and not have to rely on the file being in a particular location on disk time after time.

I'm also storing instances of these classes in a "project file" using binary serialization. I've done this to basically "package" everything together. I'm having trouble when I attempt to deserialize the MemoryStream, it seems. The problem happens when I create the image from the MemoryStream. When the following method runs after deserialization, a FileFormatexception occurs.

private void RefreshImageFromContent()
{
    BitmapImage image = null;
    if (Content != null &&
        Content.Length != 0L)
    {
        image = new BitmapImage();
        image.BeginInit();
        image.StreamSource = Content;
        image.EndInit(); //throws FileFormatException
    }

    Image = image;
}

The FileFormatException message is: "The image cannot be decoded. The image header might be corrupted." Inner Exception: "Exception from HRESULT: 0x88982F61"

My best guess right now is that something is happening to corrupt the data in BinaryContent.Content when during serialization or deserialization.

This leads me to ask 2 questions.

  1. Does anyone have any suggestions to fix this problem?
  2. Does anyone have other suggested ways to store arbitrary binary data that is going to be (de)serialized?

Please feel free to ask for clarification on anything about my question.

Thanks.

+1  A: 

What is the content.Position at image.StreamSource = Content;?

It is likely that the position of the stream is not set to the start (or the correct position in thw stream).

Aliostad
This fixed it for me. After deserialization, the stream's `Position` must have been at the end. I even reset the position at other places in my code too; I just forgot to do it here. This is another reason why using MemoryStream isn't a good idea--too annoying! haha. I want to leave the question open for a little longer to encourage other suggestions of storage methods other than `MemoryStream` and `byte[]` (courtesy of Aliostad), but I'll mark your response as the answer in the end.
Benny Jobigan