I think the best way of doing something (actually the closest to what you want as I understand it) is using Data Contract.
You need to create a data type or a set of pure data types. In instances, the will eventually form some data graph of any level of complexity. The question is, how to store it and restore back from file/stream to get exactly same thing?
With Data Contract, in contrast to traditional serialization, you do this absolutely non-intrusively. You only apply to the attribute
[DataContract]
to each type and
[DataMember]
to each member you want to persist. You don't even have to persist a tree structure, it could be more general graph of data. Don't forget you unique name space as your company URL to the
[DataContract]
— it will make your created-on-the-fly data standard world-unique!
The members you apply [DataMember] attribute to don't have to be public or internal, they cannot be even private. This is the whole point: you're responsible only on what's marked as a part of Data Contract. If you change something which is not part of the contract it will not harm your backward compatibility. You can also migrate the Contract incrementally (add members, don delete the legacy ones, better call them obsolete but keep) — in this case you backward compatibility is still preserved.
So, this is acomprehensive tool pretty much for everything. Use
System.Runtime.Serialization.DataContractSerializer
,
System.Runtime.Serialization.DataContractAttribute
,
System.Runtime.Serialization.DataMemberAttribute
. See:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx[
^].
Read this:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[
^].
See also past discussion here:
How can I utilize XML File streamwriter and reader in my form application?[
^].
—SA