1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using System;
- using System.IO;
- using System.Xml.Serialization;
- namespace WWPipeLine.Commons.SerializeHelper
- {
- /// <summary>
- /// Xml 序列化和反序列化类
- /// </summary>
- public class XmlHelper
- {
- /// <summary>
- /// 序列化对象为XML文件
- /// </summary>
- /// <typeparam name="T">序列化对象</typeparam>
- /// <param name="fileName">序列化文件路径</param>
- /// <param name="t">序列化对象</param>
- /// <returns></returns>
- public static bool SerializedToXml<T>(string fileName, T t)
- {
- try
- {
- Type paramType = t.GetType();
- XmlSerializer xmls = new XmlSerializer(paramType);
- using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
- {
- xmls.Serialize(fs, t);
- }
- return true;
- }
- catch (Exception ex)
- {
- System.Diagnostics.Debug.WriteLine("Serialize xml Error:" + ex.ToString());
- return false;
- }
- }
- /// <summary>
- /// 反序列化对象
- /// </summary>
- /// <typeparam name="T">反序列化的对象</typeparam>
- /// <param name="fileName">反序列化文件的路径</param>
- /// <param name="t">反序列化出来的路径</param>
- /// <returns></returns>
- public static bool DeSerializedFromXml<T>(string fileName, ref T t)
- {
- try
- {
- Type paramType = t.GetType();
- XmlSerializer xmls = new XmlSerializer(paramType);
- using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
- {
- t = (T)xmls.Deserialize(fs);
- }
- return true;
- }
- catch (Exception ex)
- {
- System.Diagnostics.Debug.WriteLine("DeSerialize xml Error:" + ex.ToString());
- return false;
- }
- }
- }
- }
|