Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

c# - Binary serialization and deserialization without creating files (via strings)

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 BinarySerialization
    {
        public static string SerializeObject(object o)
        {
            string result = "";

            if ((o.GetType().Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable)
            {
                BinaryFormatter f = new BinaryFormatter();
                using (MemoryStream str = new MemoryStream())
                {
                    f.Serialize(str, o);
                    str.Position = 0;

                    StreamReader reader = new StreamReader(str);
                    result = reader.ReadToEnd();
                }
            }

            return result;
        }

        public static object DeserializeObject(string str)
        {
            object result = null;

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                BinaryFormatter bf = new BinaryFormatter();
                result = bf.Deserialize(stream);
            }

            return result;
        }
    }

SerializeObject method works well, but DeserializeObject does not. I always get an exception with message "End of Stream encountered before parsing was completed". What may be wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...