123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Xml.Serialization;
- using System.Data;
- using System.Reflection;
- using System.Collections;
- namespace Ant.Service.Common
- {
- /// <summary>
- /// 序列化反序列化对象帮助类
- /// add 作者: 季健国 QQ:181589805 by 2016-03-09
- /// </summary>
- public class SerializationHelper
- {
- public SerializationHelper() { }
- /// <summary>
- /// 反序列化
- /// </summary>
- /// <param name="type">对象类型</param>
- /// <param name="filename">文件路径</param>
- /// <returns></returns>
- public static object Load(Type type, string filename)
- {
- FileStream fs = null;
- try
- {
- // open the stream...
- fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
- XmlSerializer serializer = new XmlSerializer(type);
- return serializer.Deserialize(fs);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- }
- /// <summary>
- /// 序列化
- /// </summary>
- /// <param name="obj">对象</param>
- /// <param name="filename">文件路径</param>
- public static void Save(object obj, string filename)
- {
- FileStream fs = null;
- // serialize it...
- try
- {
- fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
- XmlSerializer serializer = new XmlSerializer(obj.GetType());
- serializer.Serialize(fs, obj);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- }
- /// <summary>
- /// 序列化XML字符串
- /// </summary>
- /// <param name="obj">对象</param>
- public static string Save(object obj)
- {
- MemoryStream ms = new MemoryStream();
- System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, Encoding.Default);
- // serialize it...
- try
- {
- XmlSerializer serializer = new XmlSerializer(obj.GetType());
- serializer.Serialize(xtw, obj);
- return Encoding.Default.GetString(ms.ToArray());
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- xtw.Close();
- ms.Dispose();
- }
- }
- /// <summary>
- /// 反序列化XML字符串
- /// </summary>
- /// <param name="type">类型</param>
- /// <param name="xml">XML字符串</param>
- /// <returns></returns>
- public static object Get(Type type, string xml)
- {
- MemoryStream ms = null;
- StreamReader sr = null;
- try
- {
- XmlSerializer serializer = new XmlSerializer(type);
- ms = new MemoryStream(Encoding.Default.GetBytes(xml));
- using (sr = new StreamReader(ms, Encoding.Default))
- {
- return serializer.Deserialize(sr);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- sr.Dispose();
- sr.Close();
- ms.Dispose();
- }
- }
- }
- }
|