protobuf-net Serialize To String and Store in Database Then De Serialize

后端 未结 2 458
暗喜
暗喜 2020-12-24 07:58

I\'d like to serialize/de-serialize an object using a string. Just to note, when I serialize/de-serialize to a file everything works fine. What I\'m trying to do is get a

相关标签:
2条回答
  • 2020-12-24 08:28

    Based on the answer and the comment, I use these:

            internal static string SerializeToString_PB<T>(this T obj)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(ms, obj);
                    return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
                }
            }
            internal static T DeserializeFromString_PB<T>(this string txt)
            {
                byte[] arr = Convert.FromBase64String(txt);
                using (MemoryStream ms = new MemoryStream(arr))
                    return ProtoBuf.Serializer.Deserialize<T>(ms);
            }
    
    0 讨论(0)
  • 2020-12-24 08:29

    I am little bit lost by the use of the StreamReader in this context, it would seem to me that you could omit that and do something like below to ensure there isn't a one-way encoding happening..

    MemoryStream msTestString = new MemoryStream();
    Serializer.Serialize(msTestString, registrationBlocks);
    
    string stringBase64 = Convert.ToBase64String(msTestString.ToArray());
    
    byte[] byteAfter64 = Convert.FromBase64String(stringBase64);
    MemoryStream afterStream = new MemoryStream(byteAfter64);
    
    List<RVRegistrationBlock> CopiedBlocksString = new List<RVRegistrationBlock>();
    CopiedBlocksString = Serializer.Deserialize<List<RVRegistrationBlock>>(afterStream);
    
    0 讨论(0)
提交回复
热议问题