Protobuf-net Merge a collection into an existing file

I serialize the collection to a file using protobuf-net.

I am looking for a way to merge some more elements into an existing file.

I currently have this:

[Test]
public void CanAppend()
{
    var list = new List<Person>();

    for (int i = 0; i < 1000; i++)
       list.Add(new Person {Name = i.ToString(), Age = i});

    using (var file = File.Create("person.bin"))
    {
       Serializer.Serialize<List<Person>>(file, list);
    }

    list.Clear();

    for (int i = 1000; i < 2000; i++)
       list.Add(new Person { Name = i.ToString(), Age = i });

    using (var file = File.OpenRead("person.bin"))
    {
       Serializer.Merge<List<Person>>(file, list);
    }

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

    //Fails here    
    Assert.That(list.Count, Is.EqualTo(2000));
}

[ProtoContract]
class Person
{
   [ProtoMember(1)]
   public string Name { get; set; }

   [ProtoMember(2)]
   public int Age { get; set; }
}

But that will not work. Any ideas?

+3
source share
1 answer

Merge- operation of deserialization (used to read the stream as a delta into an existing object). Fortunately, protobuf sequences are just additive, so all you have to do is open the stream for adding (or manually move it to the end of the stream) and then call it Serialize.

using (var file = File.Open("person.bin", FileMode.Append, FileAccess.Write)) {
    Serializer.Serialize(file, list);
}
+2
source

Source: https://habr.com/ru/post/1759016/


All Articles