ObjSerialize
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace SCS.Framework.Common
{
public class ObjSerialize
{
/// <summary>
/// Serialize a object as a xml string
/// </summary>
/// <param name="obj"></param>
/// <returns>Serialize xml string</returns>
public string SerializeObj(object obj)
{
if (obj != null)
{
XmlSerializer xs = new XmlSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.None;
xs.Serialize(writer, obj);
stream.Position = 0;
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
reader.Close();
}
writer.Close();
return sb.ToString();
}
return string.Empty;
}
/// <summary>
/// Deserialize a string to system object
/// </summary>
/// <typeparam name="T">object Type</typeparam>
/// <param name="strXml">xml string</param>
/// <param name="obj">object have that Type</param>
/// <returns>Object</returns>
public T DeserializeObj<T>(string strXml, T obj)
{
if (strXml != null && strXml != string.Empty)
{
MemoryStream stream = new MemoryStream();
StreamWriter strw = new StreamWriter(stream);
strw.Write(strXml);
strw.Flush();
XmlSerializer xs = new XmlSerializer(obj.GetType());
try
{
stream.Position = 0;
object instance = xs.Deserialize(stream);
if (instance != null)
{
obj = (T)instance;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
strw.Close();
}
}
return obj;
}
/// <summary>
/// Deserialize a string to system object
/// </summary>
/// <typeparam name="T">object Type</typeparam>
/// <param name="strXml">xml file stream</param>
/// <param name="obj">object have that Type</param>
/// <returns>Object</returns>
public T DeserializeObj<T>(Stream stream, T obj)
{
if (stream != null)
{
XmlSerializer xs = new XmlSerializer(obj.GetType());
try
{
stream.Position = 0;
object instance = xs.Deserialize(stream);
if (instance != null)
{
obj = (T)instance;
}
}
catch (Exception ex)
{
throw ex;
}
}
return obj;
}
}
}