Serialize objects in file with protobuf in C#

Install-Package protobuf-net

Decorate your classes

[ProtoContract]
class Person {
    [ProtoMember(1)]
    public int Id {get;set;}
    [ProtoMember(2)]
    public string Name {get;set;}
    [ProtoMember(3)]
    public Address Address {get;set;}
}
[ProtoContract]
class Address {
    [ProtoMember(1)]
    public string Line1 {get;set;}
    [ProtoMember(2)]
    public string Line2 {get;set;}
}

Serialize your data

var person = new Person {
    Id = 12345, Name = "Fred",
    Address = new Address {
        Line1 = "Flat 1",
        Line2 = "The Meadows"
    }
};
using(var file = new FileStream(path, FileMode.Truncate)) {
    Serializer.Serialize(file, person);
    file.SetLength(file.Position);
}
if (!File.Exists(Statics.UserProtobufFile))
{
    using (var file = new FileStream(Statics.UserProtobufFile, FileMode.Create))
    {
        Serializer.Serialize(file, Statics.User);
        file.SetLength(file.Position);
    }
}
else
{
    using (var file = new FileStream(Statics.UserProtobufFile, FileMode.Truncate))
    {
        Serializer.Serialize(file, Statics.User);
        file.SetLength(file.Position);
    }
}

Deserialize your data

Person newPerson;
using (var file = File.OpenRead("person.bin")) {
    newPerson = Serializer.Deserialize<Person>(file);
}

References
https://github.com/protobuf-net/protobuf-net
https://stackoverflow.com/questions/20369302/how-to-serialize-several-objects-in-one-file-in-c-sharp-with-protobuf
https://stackoverflow.com/questions/2152978/using-protobuf-net-i-suddenly-got-an-exception-about-an-unknown-wire-type