反序列化一个用 XmlSerializer 序列化的 byte[] [英] de-serialze a byte[] that was serialzed with XmlSerializer

查看:29
本文介绍了反序列化一个用 XmlSerializer 序列化的 byte[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用以下代码序列化的 byte[]:

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......

有什么区别,我怎样才能将磁盘中的数据恢复到 byte[] 中?

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

注意:数据是一个 Bitmap,格式为 png,如下所示:

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);
    }
 }

推荐答案

iVBORw0KGgoAAAANSUhEUgAAAPAAAAFACAIAAAANimYEAAAAA...

是二进制数据的 base64 编码表示.

is base64 encoded representation of the binary data.

0x89504E470D0A1A0A0000000D49484452000000F000000140080...

是十六进制.

要从磁盘取回数据,请使用 XmlSerializer 并将其反序列化回原始对象:

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);
    }
}

但如果您只有 base64 字符串表示,您可以使用 FromBase64String 方法:

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

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

备注:确保您始终处理一次性资源,例如流和文本读取器和写入器.在您的 SerializeObject<T> 方法和 ImageAsBytes 属性的 getter 和 setter 方法中,情况似乎并非如此.

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.

这篇关于反序列化一个用 XmlSerializer 序列化的 byte[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆