Datacontract serialization-how to serialize datacontract collections (Dictionary, list, etc)
Objects in these sets are defined as datacontract. The key lies in the object type in the container, which must be specified through knowstype:
Using system; <br/> using system. collections. generic; <br/> using system. collections; <br/> using system. text; <br/> using system. io; <br/> using system. runtime. serialization; </P> <p> namespace knowntypeattributeexample <br/>{< br/> class Program <br/>{< br/> static void main (string [] ARGs) <br/>{< br/> try <br/> {<br/> testclass Tc = new testclass () {id = "123", name = "ABC "}; <br/> dictionary <string, testclass> dict = new dictionary <string, testclass> (); <br/> dict. add ("test", Tc); </P> <p> List <type> knowntypes = new list <type> (); <br/> knowntypes. add (typeof (testclass); </P> <p> serialize <dictionary <string, testclass> ("D: // knowntypeattributeexample. XML ", knowntypes, dict); <br/> dictionary <string, testclass> dict2 = deserialize <dictionary <string, testclass> (" D: // knowntypeattributeexample. XML ", knowntypes); </P> <p> testclass TC2 = dict2 [" test "]; <br/> console. writeline ("ID: {0} Name: {1}", tc2.id, tc2.name); <br/>}< br/> catch (serializationexception exc) <br/> {<br/> console. writeline ("{0 }:{ 1}", exc. message, <br/> exc. stacktrace); <br/>}< br/> finally <br/> {<br/> console. writeline ("press enter to exit... "); <br/> console. readline (); <br/>}</P> <p> Public static void serialize <t> (string path, list <type> knowntypes, t) <br/>{< br/> datacontractserializer SER = <br/> New datacontractserializer (typeof (t), knowntypes ); </P> <p> filestream FS = new filestream (path, filemode. create); <br/> using (FS) <br/>{< br/> Ser. writeobject (FS, T); <br/>}</P> <p> Public static t deserialize <t> (string path, list <type> knowntypes) <br/>{< br/> datacontractserializer SER = <br/> New datacontractserializer (typeof (t), knowntypes ); <br/> filestream FS = new filestream (path, filemode. open); <br/> t obj = default (t); <br/> using (FS) <br/> {<br/> OBJ = (t) Ser. readobject (FS); <br/>}< br/> return OBJ; <br/>}</P> <p> [datacontract] <br/> public class testclass <br/> {<br/> [datamember] <br/> Public String name {Get; set ;}< br/> [datamember] <br/> Public String ID {Get; set ;} <br/>}</P> <p >}< br/>