Binary serialization and deserialization without creating files (via strings)

后端 未结 2 1609
暖寄归人
暖寄归人 2020-12-10 01:34

I\'m trying to create a class that will contain functions for serializing/deserializing objects to/from string. That\'s what it looks like now:

public class          


        
相关标签:
2条回答
  • 2020-12-10 01:56

    Use UTF8 Base64 encoding instead of ASCII, for both encoding and decoding.

    0 讨论(0)
  • 2020-12-10 02:05

    The result of serializing an object with BinaryFormatter is an octet stream, not a string.
    You can't just treat the bytes as characters like in C or Python.

    Encode the serialized object with Base64 to get a string instead:

    public static string SerializeObject(object o)
    {
        if (!o.GetType().IsSerializable)
        {
            return null;
        }
    
        using (MemoryStream stream = new MemoryStream())
        {
            new BinaryFormatter().Serialize(stream, o);
            return Convert.ToBase64String(stream.ToArray());
        }
    }
    

    and

    public static object DeserializeObject(string str)
    {
        byte[] bytes = Convert.FromBase64String(str);
    
        using (MemoryStream stream = new MemoryStream(bytes))
        {
            return new BinaryFormatter().Deserialize(stream);
        }
    }
    
    0 讨论(0)
提交回复
热议问题