Mark Muis
Mark Muis

Reputation: 1

C# serialize only values into a byte stream

Is there any possibility to automatically serialize properties of a class into a byte[] array or stream.

Stream stream = File.Open(@"C:/traiBin.bin", FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, this.rcpt);
stream.Close();

This example above serialized the whole class including namespaces, class name, variable names etc. If there is no automated solution it will do it by hand.

Regards, Mark

Upvotes: 0

Views: 783

Answers (3)

fofolevrai
fofolevrai

Reputation: 127

You should definitly take a look at BinarySerializer library which generates stream without any extra-overhead on data.

Bellow an example and it's result:

Class to serialize:

public class Packet
{
    [FieldOrder(0)]
    public byte StartByte = 0x88;

    [FieldOrder(1)]
    public byte Length { get; set; }

    [FieldOrder(2)]
    [FieldChecksum(nameof(Checksum), Mode = ChecksumMode.TwosComplement)]
    public byte[] Data { get; set; }

    [FieldOrder(3)]
    public byte Checksum { get; set; }
}

Usage:

public void Serialize_UTxxxx_Should_SerializePacketWithDataOnly()
{
    var stream = new MemoryStream();
    var serializer = new BinarySerializer();
    //  ASCII 'Hello world!' in hex format
    var dataIn = new byte[] { 0x41, 0x61, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21 };

    Packet pck = new Packet()
    {
        Length = Convert.ToByte(dataIn.Length + sizeof(byte) + sizeof(byte) + sizeof(byte)),
        Data = dataIn
    };

    serializer.Serialize(stream, pck);

    byte[] dataOut = stream.ToArray();
    Debug.WriteLine(Encoding.UTF8.GetString(dataOut));
    Thread.Sleep(5000);
}

Result:

Caution: Here, checksum is only calculated from the Data values

enter image description here

Upvotes: 1

Jonathan Dickinson
Jonathan Dickinson

Reputation: 9218

Marc Gravell's protobuf implementation supports the attributed model, as well as DataContracts - protobuf is also pretty lean when it comes the final size of the data.

Upvotes: 0

Tigran
Tigran

Reputation: 62246

I think you have to :

Or implement your own serialization mechanism ( can be not so hard based on your requirements), so in stream you will have kind of header that identifies the type saved and after type data stream, after another header and its type data stream again, and so on...

Or you can use something like this http://www.codeproject.com/KB/cs/generic_deep_cloning.aspx . Just an example of serialization, that author of article uses for deep cloning purposes.

Upvotes: 0

Related Questions