Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize/Deserialze to a string C#

First time playing with serialization in C#... any help would be greatly appreciated! The following are my generic serializer and deserializer:

    public static string SerializeObject<T>(T objectToSerialize)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream memStr = new MemoryStream();

        try
        {
            bf.Serialize(memStr, objectToSerialize);
            memStr.Position = 0;

            return Convert.ToBase64String(memStr.ToArray());
        }
        finally
        {
            memStr.Close();
        }
    }

    public static T DeserializeObject<T>(string str)
    {
        BinaryFormatter bf = new BinaryFormatter();
        byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
        MemoryStream ms = new MemoryStream(b);

        try
        {
            return (T)bf.Deserialize(ms);
        }
        finally
        {
            ms.Close();
        }
    }

This is the object I am trying to serialize:

[Serializable()]
class MatrixSerializable : ISerializable
{
    private bool markerFound;
    private Matrix matrix;

    public MatrixSerializable( Matrix m, bool b)
    {
        matrix = m;
        markerFound = b;
    }

    public MatrixSerializable(SerializationInfo info, StreamingContext ctxt)
    {
        markerFound = (bool)info.GetValue("markerFound", typeof(bool));

        matrix = Matrix.Identity;

        if (markerFound)
        {

            //deserialization code
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    {
        // serialization code
    }

    public Matrix Matrix
    {
        get { return matrix; }
        set { matrix = value; }
    }

    public bool MarkerFound
    {
        get { return markerFound; }
        set { markerFound = value; }
    }
}

And an example of how am running it:

        MatrixSerializable ms = new MatrixSerializable(Matrix.Identity * 5, true);

        string s = Serializer.SerializeObject<MatrixSerializable>(ms);

        Console.WriteLine("serialized: " + s);

        ms = Serializer.DeserializeObject<MatrixSerializable>(s);

        Console.WriteLine("deserialized: " + ms.Matrix + " " + ms.MarkerFound);

When I try to run this I get an error "SerializationException was unhandled: The input stream is not a valid binary format. The starting contents (in bytes) are: 41-41-45-41-41-41-44-2F-2F-2F-2F-2F-41-51-41-41-41 ..."

Any advice on what I am doing wrong or how to fix this would be greatly appreciated!

like image 256
ElfsЯUs Avatar asked May 01 '12 00:05

ElfsЯUs


1 Answers

You are using Base64 to convert byte array to string and GetUtf8 bytes to convert from string back to byte array.

Replace System.Text.Encoding.UTF8.GetBytes(str); with Convert.FromBase64String(str);

like image 178
Alexei Levenkov Avatar answered Sep 24 '22 22:09

Alexei Levenkov