public static class Utility
{
/// <summary>
/// 对象序列化成 XML String
/// </summary>
public static string XmlSerialize<T>(T obj)
{
string xmlString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
xmlSerializer.Serialize(ms, obj);
xmlString = Encoding.UTF8.GetString(ms.ToArray());
}
return xmlString;
}
/// <summary>
/// XML String 反序列化成对象
/// </summary>
public static T XmlDeserialize<T>(string xmlString)
{
T t = default(T);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
{
using (XmlReader xmlReader = XmlReader.Create(xmlStream))
{
Object obj = xmlSerializer.Deserialize(xmlReader);
t = (T)obj;
}
}
return t;
}
/// <summary>
/// 二进制序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">要序列化的对象</param>
public static byte[] BinarySerialize<T>(T obj)
{
byte[] binObj = null;
using(MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
binObj = ms.GetBuffer();
}
return binObj;
}
/// <summary>
/// 二进制反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="stream"></param>
/// <returns></returns>
public static T BinaryDeserialize<T>(byte[] binObj)
{
T t = default(T);
using (MemoryStream ms = new MemoryStream(binObj, false))
{
BinaryFormatter bf = new BinaryFormatter();
t = (T)bf.Deserialize(ms);
}
return t;
}
/// <summary>
/// 执行XML序列化并保存成文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="fileName"></param>
public static void SerializeToXMLFile<T>(T obj, string fileName)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
xmlSerializer.Serialize(fs, obj);
fs.Flush();
}
}
/// <summary>
/// 从XML文件反序列化出Object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public static T DeserializeFromXMLFile<T>(string fileName)
{
T t = default(T);
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
t = (T)xmlSerializer.Deserialize(fs);
}
return t;
}
/// <summary>
/// Clone object by xml serialize.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T XmlClone<T>(T obj)
{
return Utility.XmlDeserialize<T>(Utility.XmlSerialize<T>(obj));
}
/// <summary>
/// Clone object by binary serialize
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T BinaryClone<T>(T obj)
{
return Utility.BinaryDeserialize<T>(Utility.BinarySerialize<T>(obj));
}
}
.net C# XML / Binary 序列化反序列化代码示例
最新推荐文章于 2024-11-08 09:48:14 发布