ORDINA BLOGT

XML Serialization with C - update

My preferred way to serialize an object

  • 5 februari 2013

This is now my preferred way to serialize an object. You can choose the XML Serializer and the DataContract Serializer;
 

public class XmlSerializer
 {
    public static MemoryStream SerializeToMemoryStream<T>(T t)
    {
       var memorystream = new MemoryStream();
       var s = new System.Xml.Serialization.XmlSerializer(typeof (T));
 
      xmlserializer.Serialize(XmlWriter.Create(memorystream), t);
 
      memorystream.Flush();
      memorystream.Seek(0, SeekOrigin.Begin);
 
      return memorystream;
    }
 
   public static string SerializeToString<T>(T t)
    {
       return SerializeToString(t, Encoding.UTF8);
    }
 
   public static string SerializeToString<T>(T t, Encoding encoding)
    {
       var settingsString = encoding.GetString(SerializeToMemoryStream(t).ToArray());
       return settingsString;
    }
 }
 
        public class DatacontractSerializer
         {
             public static MemoryStream SerializeToMemoryStream<T>(T t)
             {
                 var stream = new MemoryStream();
                 var s = new

 System.Runtime.Serialization.DataContractSerializer(typeof(T));
                 s.WriteObject(XmlWriter.Create(stream), t);
                 stream.Flush();
                 stream.Seek(0, SeekOrigin.Begin);
                 return stream;
             }
 
            public static string SerializeToString<T>(T t)
             {
                 return SerializeToString(t, Encoding.UTF8);
             }
 
            public static string SerializeToString<T>(T t, Encoding encoding)
             {
                 var settingsString = encoding.GetString(SerializeToMemoryStream(t).ToArray());
                 return settingsString;
             }
         }
     }