Binary serialization and deserialization without creating files (via strings)

Posted by the_V on Stack Overflow See other posts from Stack Overflow or by the_V
Published on 2010-05-18T22:52:20Z Indexed on 2010/05/18 23:00 UTC
Read the original article Hit count: 207

Filed under:
|
|

Hi,

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?

© Stack Overflow or respective owner

Related posts about serialization

Related posts about .NET