Friday, May 1, 2009

Code to Serialize Object in C# .Net

Please use the below method if you want to serialize any object. This method returns you a string which is XML consists of all public properties and public data members of the object passed. It perfectly works for any type of reference type object.

String SerializeObject(Object obj)
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();

XmlSerializer xs = new XmlSerializer(obj.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

xs.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;

catch (Exception e)
return null;