C# Object Binary Serialization

前端 未结 6 1737
-上瘾入骨i
-上瘾入骨i 2020-12-05 02:17

I want to make a binary serialize of an object and the result to save it in a database.

Person person = new Person();
person.Name = \"something\";

MemoryStr         


        
6条回答
  •  广开言路
    2020-12-05 03:12

    Here's the sample. TData must be marked [Serializable] and all fields type also.

        private static TData DeserializeFromString(string settings)
        {
            byte[] b = Convert.FromBase64String(settings);
            using (var stream = new MemoryStream(b))
            {
                var formatter = new BinaryFormatter();
                stream.Seek(0, SeekOrigin.Begin);
                return (TData)formatter.Deserialize(stream);
            }
        }
    
        private static string SerializeToString(TData settings)
        {
            using (var stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, settings);
                stream.Flush();
                stream.Position = 0;
                return Convert.ToBase64String(stream.ToArray());
            }
        }
    

提交回复
热议问题