I have one file. You need to serialize several objects at random. How can I in C #?

I have one file and need to serialize several objects of the same class when a new object is created. I cannot store them in arrays, because I need to serialize their instance created by the object. Please help me.

+6
object c # serialization
source share
3 answers

What serialization mechanism do you use? XmlSerializer can be a problem due to the root of the node and things like namespace declarations, which are a little complicated to get a snapshot - plus this is not very good for partial deserialization. BinaryFormatter very fragile to start with - I do not recommend it in most cases.

One parameter may be protobuf-net ; it is a binary serializer (using the Google protocol format, the "protocol" is efficient, portable, and version-stable). You can serialize multiple objects into a stream using Serializer.SerializeWithLengthPrefix . To deserialize the same elements, Serializer.DeserializeItems returns an IEnumerable<T> deserialized elements - or you can easily make TryDeserializeWithLengthPrefix public (it is currently closed, but the source is available).

Just write each object to a file after its creation - the work done.

If you want to give an example, tell me, although the block here gives an overview.

Basically it will 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 } } 
+7
source share

See the answer here .

In short, just serialize everything into the same file stream, and then deserialize. dotNet will know the size of each object

0
source share

For each returned object, we convert it to a Base64Encoded line and save it as one line in a text file. Thus, in this file, each line will have a serialized object in the line. While reading, we will read the file one line at a time and deserialize this Base64 encoding in our object. Easy .. so try the code.

http://www.codeproject.com/KB/cs/serializedeserialize.aspx?display=Print

0
source share

All Articles