How do I store arbitrary binary data in a binary serialized class?
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:
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 &a开发者_高级运维mp;&
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.
- Does anyone have any suggestions to fix this problem?
- 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.
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).
精彩评论