using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YG.Lib { public class XmlLib { private static XmlLib xml = new XmlLib(); public static XmlLib Instance { get { return xml; } } /// /// 保存对象到xml文件中 /// /// 需要序列化的对象的名称 /// 对象实体 /// 需要保存对象的xml的路径 /// public bool XmlSave(object ob, string xmlpath) { try { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); System.IO.Stream stream = new System.IO.FileStream(xmlpath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); serializer.Serialize(stream, ob); stream.Close(); return true; } catch (Exception e) { Log.Instance.WriteLogAdd($"35-->{e.Message}"); return false; } } /// /// 打开xml对象 /// /// 需要转换的对象类型 /// config路径 /// public T XmlOpen(string xmlpath) { T t; try { if (System.IO.File.Exists(xmlpath)) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); System.IO.Stream stream = new System.IO.FileStream(xmlpath, System.IO.FileMode.OpenOrCreate); t = (T)serializer.Deserialize(stream); stream.Close(); return t; } else { //需要添加一个提示信息, 或者写入日志的操作 return default(T); } } catch(Exception e) { Log.Instance.WriteLogAdd($"67-->{ e.Message}"); return default(T); } // return t } } }