Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

serialization - I have a Single File And need to serialize multiple objects randomly. How can I in c#?

I have a single file and need to serialize multiple objects of the same class when ever a new object is created. I can't store them in arrays as I need to serialize them the instance an object is create. Please, help me.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

What serialization mechanism are you using? XmlSerializer might be a problem because of the root node and things like namespace declarations, which are a bit tricky to get shot of - plus it isn't great at partial deserializations. BinaryFormatter is very brittle to begin with - I don't recommend it in most cases.

One option might be protobuf-net; this is a binary serializer (using Google's "protocol buffers" format - efficient, portable, and version-tolerant). You can serialize multiple objects to a stream with Serializer.SerializeWithLengthPrefix. To deserialize the same items, Serializer.DeserializeItems returns an IEnumerable<T> of the deserialized items - or you could easily make TryDeserializeWithLengthPrefix public (it is currently private, but the source is available).

Just write each object to file after you have created it - job done.

If you want an example, please say - although the unit tests here give an overview.

It would basically be something like (untested):

using(Stream s = File.Create(path))
{
    Serializer.SerializeWithLengthPrefix(s, command1, PrefixStyle.Base128, 0);
    ... your code etc
    Serializer.SerializeWithLengthPrefix(s, commandN, PrefixStyle.Base128, 0);
}
...
using(Stream s = File.OpenRead(path)) {
    foreach(Command command in
           Serializer.DeserializeItems<Command>(s, PrefixStyle.Base128, 0))
    {
       ... do something with command
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...