Calling BinaryFormatter.Serialize() incrementally

  • Thread starter Thread starter Sebastian
  • Start date Start date
S

Sebastian

I have a List of objects. I have a requirement to periodically
Serialize the List to disk incrementally i.e. Serialize the List from
the last write to disk.
Is this possible?

calling BinaryFormatter.Serialize(FileStream, List) multiple times
does not seem to append the List from the subsequent call.

e.g.
BinaryFormatter.Serialize(FileStream, list1) //Serializes list1
BinaryFormatter.Serialize(FileStream, list2) //Does not seem to
append list2
 
I have a List of objects. I have a requirement to periodically
Serialize the List to disk incrementally i.e. Serialize the List from
the last write to disk.
Is this possible?

calling BinaryFormatter.Serialize(FileStream, List) multiple times
does not seem to append the List from the subsequent call.

e.g.
BinaryFormatter.Serialize(FileStream, list1) //Serializes list1
BinaryFormatter.Serialize(FileStream, list2) //Does not seem to
append list2

It does.

But your code needs to read it.

Example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace E
{
public class Program
{
public static void Main(string[] args)
{
List<string> lst = new List<string>();
lst.Add("A");
lst.Add("BB");
BinaryFormatter binser = new BinaryFormatter();
using(Stream f = new FileStream(@"C:\bin.bin",
FileMode.Create, FileAccess.Write))
{
binser.Serialize(f, lst);
}
// bin.bin now contains "A", "BB"
using(Stream f = new FileStream(@"C:\bin.bin",
FileMode.Open, FileAccess.Read))
{
while(f.Position < f.Length)
{
List<string> rlst =
(List<string>)binser.Deserialize(f);
foreach(string s in rlst)
{
Console.WriteLine(s);
}
}
}
lst.Add("CCC");
using(Stream f = new FileStream(@"C:\bin.bin",
FileMode.Append, FileAccess.Write))
{
binser.Serialize(f, lst);
}
// bin.bin now contains "A", "BB", "A", "BB", "CCC"
using(Stream f = new FileStream(@"C:\bin.bin",
FileMode.Open, FileAccess.Read))
{
while(f.Position < f.Length)
{
List<string> rlst =
(List<string>)binser.Deserialize(f);
foreach(string s in rlst)
{
Console.WriteLine(s);
}
}
}
Console.ReadKey();
}
}
}

Arne
 
Back
Top