Sayfalar

21 Mart 2012 Çarşamba

Serilizing objects to string and Deserilizing objects from string


If you like working with object this solution help you. You may save your class and use this class when you want.
Code

public static class Extensions
{
 public static object GetClassFromString<T>(this string str)
    {
        T rtnObject;
        using (StringReader reader = new StringReader(str))
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            rtnObject = (T)ser.Deserialize(reader);
            reader.Close();
        }
        return rtnObject;
    }
  public static string GetXmlStringFromClass(this object obje)
        {
            string XmlData = null;
            using (MemoryStream mstr = new MemoryStream())
            {
                XmlTextWriter xtw = new XmlTextWriter(mstr, Encoding.Default);
                XmlSerializer xs = new XmlSerializer(obje.GetType());
                xs.Serialize(xtw, obje);
                UTF8Encoding enc = new UTF8Encoding();
                XmlData = enc.GetString(mstr.ToArray());
                xtw.Close();
                mstr.Close();
            }
            return XmlData;
        }
}  

Hiç yorum yok:

Yorum Gönder