c# - How to save/restore serializable object to/from file? -
i have list of objects , need save somewhere in computer. have read forums , know object has serializable
. nice if can example. illustration if have following:
[serializable] public class someclass { public string someproperty { get; set; } } someclass object1 = new someclass { someproperty = "somestring" };
but how can store object1
somewhere in computer , later retrieve?
you can utilize following:
/// <summary> /// serializes object. /// </summary> /// <typeparam name="t"></typeparam> /// <param name="serializableobject"></param> /// <param name="filename"></param> public void serializeobject<t>(t serializableobject, string filename) { if (serializableobject == null) { return; } seek { xmldocument xmldocument = new xmldocument(); xmlserializer serializer = new xmlserializer(serializableobject.gettype()); using (memorystream stream = new memorystream()) { serializer.serialize(stream, serializableobject); stream.position = 0; xmldocument.load(stream); xmldocument.save(filename); stream.close(); } } grab (exception ex) { //log exception here } } /// <summary> /// deserializes xml file object list /// </summary> /// <typeparam name="t"></typeparam> /// <param name="filename"></param> /// <returns></returns> public t deserializeobject<t>(string filename) { if (string.isnullorempty(filename)) { homecoming default(t); } t objectout = default(t); seek { xmldocument xmldocument = new xmldocument(); xmldocument.load(filename); string xmlstring = xmldocument.outerxml; using (stringreader read = new stringreader(xmlstring)) { type outtype = typeof(t); xmlserializer serializer = new xmlserializer(outtype); using (xmlreader reader = new xmltextreader(read)) { objectout = (t)serializer.deserialize(reader); reader.close(); } read.close(); } } grab (exception ex) { //log exception here } homecoming objectout; }
c# serialization stream
No comments:
Post a Comment