Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize on to existing file?

Let say I have a file that contains a serialized object by BinaryFomatter. Now I want to be able to serialize another object and APPEND this on that existing file.

How can I do it?

like image 916
user50819 Avatar asked Apr 29 '09 18:04

user50819


People also ask

What does it mean to serialize a file?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed.


1 Answers

This is indeed possible. The code below appends the object.

using (var fileStream = new FileStream("C:\file.dat", FileMode.Append))
{
    var bFormatter = new BinaryFormatter();
    bFormatter.Serialize(fileStream, objectToSerialize);
}

The following code de-serializes the objects.

var list = new List<ObjectToSerialize>();    

using (var fileStream = new FileStream("C:\file.dat", FileMode.Open))
{
    var bFormatter = new BinaryFormatter();
    while (fileStream.Position != fileStream.Length)
    {
         list.Add((ObjectToSerialize)bFormatter.Deserialize(fileStream));
    }
}

Note for this to work the file must only contain the same objects.

like image 164
Magpie Avatar answered Oct 25 '22 15:10

Magpie