agnieszka
agnieszka

Reputation: 15355

.NET: How to binary serialize an object with attribute [DataContract]?

Class marked as [DataContract] can't be ISerializable at the same time. OK, so how can I serialize this type of object to a binary stream?

private byte[] GetRoomAsBinary(Room room)
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, room);
            return stream.ToArray();
        }

I can't make it work without Room being ISerializable. How can I get a byte array from object some other way?

Upvotes: 8

Views: 9816

Answers (3)

Patrik Svensson
Patrik Svensson

Reputation: 13874

Code to serialize and deserialize using binary formatter:

public static class BinarySerializer
{
    public static byte[] Serialize<T>(T obj)
    {
        var serializer = new DataContractSerializer(typeof(T));
        var stream = new MemoryStream();
        using (var writer = 
            XmlDictionaryWriter.CreateBinaryWriter(stream))
        {
            serializer.WriteObject(writer, obj);
        }
        return stream.ToArray();
    }

    public static T Deserialize<T>(byte[] data)
    {
        var serializer = new DataContractSerializer(typeof(T));
        using (var stream = new MemoryStream(data))
        using (var reader = 
            XmlDictionaryReader.CreateBinaryReader(
                stream, XmlDictionaryReaderQuotas.Max))
        {
            return (T)serializer.ReadObject(reader);
        }
    }
}

Usage:

public void TestBinarySerialization()
{
    // Create the person object.
    Person person = new Person { Name = "John", Age = 32 };

    // Serialize and deserialize the person object.
    byte[] data = BinarySerializer.Serialize<Person>(person);
    Person newPerson = BinarySerializer.Deserialize<Person>(data);

    // Assert the properties in the new person object.
    Debug.Assert(newPerson.Age == 32);
    Debug.Assert(newPerson.Name == "John");
}

Upvotes: 30

agnieszka
agnieszka

Reputation: 15355

The solution is to use DataContractSerializer to serialize the object.

Upvotes: 2

Timores
Timores

Reputation: 14589

That's the principle of binary serialization: only [Serializable] classes can be serialized (although I may have read that this restriction was lifted recently). If you want to take control of the serialization process, implement ISerializable.

If the Room class has non-serializable members, you will need ISerializable, too.

What are the members of Room ?

Upvotes: 0

Related Questions