de-serialze a byte[] that was serialzed with XmlSe

2019-08-12 17:13发布

I have a byte[] that was serialized with the following code:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    TextWriter textWriter = new StreamWriter(filename);

    xmlSerializer.Serialize(textWriter, toSerialize);
    textWriter.Close();
}

problem is the data serialized looks like this:

iVBORw0KGgoAAAANSUhEUgAAAPAAAAFACAIAAAANimYEAAAAAXNSR0IArs4c6QAAAARnQU1BAACx......

when it gets stored in my database it looks like this:

0x89504E470D0A1A0A0000000D49484452000000F00000014008020000000D8A660400000001......

What is the difference, and how can I get the data from the disk back into a byte[]?


Note: the data is a Bitmap formatted as a png like this:

public byte[] ImageAsBytes
{
    get
    {
        if (_image != null)
        {
            MemoryStream stream = new MemoryStream();
            _image .Save(stream, ImageFormat.Png);
            return stream.ToArray();
        }
        else
        {
            return null;
        }
    }
    set
    {

        MemoryStream stream = new MemoryStream(value);
        _image = new Bitmap(stream);
    }
 }

1条回答
Lonely孤独者°
2楼-- · 2019-08-12 18:01
iVBORw0KGgoAAAANSUhEUgAAAPAAAAFACAIAAAANimYEAAAAA...

is base64 encoded representation of the binary data.

0x89504E470D0A1A0A0000000D49484452000000F000000140080...

is hexadecimal.

To get the data back from the disk use XmlSerializer and deserialize it back to the original object:

public static T DeserializeObject<T>(string filename)
{
    var serializer = new XmlSerializer(typeof(T));
    using (var reader = XmlReader.Create(filename))
    {
        return (T)serializer.Deserialize(reader);
    }
}

But if you only have the base64 string representation you could use the FromBase64String method:

byte[] buffer = Convert.FromBase64String("iVBORw0KGgoAAANimYEAAAAA...");

Remark: make sure you always dispose disposable resources such as streams and text readers and writers. This doesn't seem to be the case in your SerializeObject<T> method nor in the getter and setter of the ImageAsBytes property.

查看更多
登录 后发表回答