Chi Chan
Chi Chan

Reputation: 12420

protobuf-net Merge collection to existing file

I have serialized a collection to a file using protobuf-net.

I am looking for a way to merge a few more items to the existing file.

Currently I 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 it doesn't work. Any ideas?

Upvotes: 3

Views: 1177

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064104

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

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

Upvotes: 3

Related Questions