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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With