tags:

views:

14

answers:

1

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?

+1  A: 

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);
}
Marc Gravell
Thank you Marc. Great job on protobuf-net btw. I am serializing a massive amount of data and nothing worked for me so far except protobuf-net! Many Thanks!
Chi Chan