My best advice is using Data Contract and
DataContractSerializer
with
StreamWriter
and
StreamReader
or whatever stream-related class you may want.
This is the only unobtrusive way of serialization available in .NET (you can use v.3.5 or v.4.0). Also, it can save and restore any arbitrary object graph, not only object tree or single object. This way is also the best in terms of ease-of-use and supportability. For common-use purposes (and also for remoting, WCF) you can nearlt always consider all other ways as obsolete or inferior.
You simply add the attribute
[DataContract]
to every type involved in the model to be stored/restored; better always use your own name space Web URL through the
Namespace
attribute parameter (property). Then, apply attribute
[DataMember]
to every member you want to persist. These members does not even have to be public, or properties; members can be collections, arrays -- virtually no limitation. Apparently, these steps will not modify your class hierarchy, will not modify any behavior -- nothing.
Now, if you want to modify your classes, you should be careful to provide incremental behavior with old files, but only for those members which are part of contract (marked with
[DataMember]
). After all, if have a contract, you're only responsible for contract items. When you simple add more
[DataMember]
members, your old data remains usable; new members will automatically assume default values.
Finally, create you contact serializer based on your top-level object's type:
DataContractSerializer ser =
new DataContractSerializer(typeof(Top));
Top of object graph to store in your stream:
Top top =
ser.WriteObject(xmlWriter, top);
Top newGraph = (Top)ser.ReadObject(xmlReader);
<code>
ReadObject and
WriteObject
will work with
XmlReader/XmlWriter
,
XmlDictionaryReader/XmlDictionaryWriter
, respectively, and any Stream.
You can find pretty good documentation and samle code in Microsof help:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx and
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx.
Will it help you? Please try and ask further questions.
Thank you.