how to serialize several objects in one file in C# with protobuf

c#, protocol-buffers, serialization

Solution

The "protocol buffers" format is not terminated (this is by Google's design, so that messages can be merged by concatenation). The side-effect of this is that if you simply serialize multiple times, deserializing treats it all as one message. Fortunately, protobuf-net makes it easy to do what you want:

Serializer.SerializeWithLengthPrefix(file, p1, PrefixStyle.Base128, 1);
Serializer.SerializeWithLengthPrefix(file, p2, PrefixStyle.Base128, 1);
// etc

and:

nP1 = Serializer.DeserializeWithLengthPrefix<Person>(file,PrefixStyle.Base128,1);
nP2 = Serializer.DeserializeWithLengthPrefix<Person>(file,PrefixStyle.Base128,1);
// etc

An alternative approach is to create a wrapper object - a `PersonWrapper` or `People` or whatever you want to call it - that encapsulates everything you want to serialize. This could be as a `List<Person>`, or as individual properties `Person0`, `Person1` etc.

var wrapper = new PersonWrapper { ... };
Serializer.Serialize(file, wrapper);
//...
var wrapper = Serializer.Deserialize<PersonWrapper>(file);

Finally, you could just serialize a list:

List<Person> people = ...
Serializer.Serialize(file, people);
...
var people = Serializer.Deserializer<List<Perosn>>(file);

Problem

I have the class `Person`, and I want to have several instances of it, and I want to serialize these in one file. How can I do it? I mustn't create a list of `Person` then serialize this. I want can to deserialize one instance of class that save (for example fourth instance that saved). how can I do it? Person Class : ``` [ProtoContract] class Person { public Person() { } [ProtoMember(1)] public int a; public Person(int d) { a = d; } } ``` method to serialize: ``` public void serialize() { Person p1 = new Person(1); Person p2 = new Person(2); Person p3 = new Person(3); Person p4 = new Person(4); Person p5 = new Person(5); FileStream file = File.Create("person.bin") ; Serializer.Serialize(file, p1); Serializer.Serialize(file, p2); Serializer.Serialize(file, p3); Serializer.Serialize(file, p4); Serializer.Serialize(file, p5); file.Close(); } ``` method to deserialze : ``` public void deserialize() { Person nP1, nP2,nP3,nP4,nP5; FileStream file = File.OpenRead("person.bin"); nP1 = Serializer.Deserialize<Person>(file); nP2 = Serializer.Deserialize<Person>(file); nP3 = Serializer.Deserialize<Person>(file); nP4 = Serializer.Deserialize<Person>(file); nP5 = Serializer.Deserialize<Person>(file); file.Close(); } ```

Original source