Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...