using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace Utility { public class Serialization { // 序列化 public static void EnS(string fileName = @"D:\test.xml", object obj = null) { fileName = Guid.NewGuid().ToString() + ".xml"; obj = Guid.NewGuid(); using (Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { using (XmlWriter writer = XmlWriter.Create(stream)) { try { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add(string.Empty, string.Empty); XmlSerializer xmls = new XmlSerializer(obj.GetType()); xmls.Serialize(writer, obj, ns); } catch (Exception exp) { string message = string.Format("保存{0}时发生错误", obj.GetType().Name); throw new Exception(message); } } } } // 反序列化 public static T Load<T>(string fileName = @"D:\test.xml") { using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { using (XmlReader reader = XmlReader.Create(stream)) { try { XmlSerializer xmls = new XmlSerializer(typeof(T)); return (T)xmls.Deserialize(reader); } catch (Exception exp) { string message = string.Format("装载{0}时发生错误", typeof(T).Name); throw new Exception(message, exp); } } } } } }
时间: 2024-10-22 04:03:55