本文主要是介绍关于C#读写XML的公用类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
XmlHelper有很多种写法,以泛型的方式保存和读取xml,可以做到像下面这么简化又实用:
调用处 var sysParam = XmlHelper.LoadFromXML<TSysParam>(ApplicationDir.SystemParamFile);
//无参数文件时,初始化系统参数到XML文件
XmlHelper.SaveAsXML(ApplicationDir.SystemParamFile, param);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;namespace Infrastructure
{public static class XmlHelper{/// <summary>/// 读取以xml格式保存的对象,如果文件不存在则自动创建,触发相关代码/// </summary>/// <typeparam name="T">类型参数</typeparam>/// <param name="filename">文件路径</param>/// <returns></returns>public static T LoadFromXML<T>(string fileName, Action IfFileNotExist = null){T o = default(T);try{if (!File.Exists(fileName)){if (IfFileNotExist != null)IfFileNotExist.DynamicInvoke(fileName);SaveAsXML(fileName, Activator.CreateInstance<T>());}using (FileStream fs = File.OpenRead(fileName)){o = LoadFromXML<T>(fs);fs.Close();fs.Dispose();}}catch (Exception e){if (File.Exists(fileName)){//const string path = "配置备份";//if (!Directory.Exists(path))// Directory.CreateDirectory(path);File.Copy(fileName,Path.Combine(Comm.AppDir, DateTime.Now.ToString("yyyy_MM_dd hh_mm_ss") + ".xml"), true);Comm.InfoMessage($"加载XML异常备份操作, 请查看文件{fileName}");}throw new Exception($"加载XML异常: {e.Message}: {e.StackTrace}");}return o;}/// <summary>/// 将对象以xml格式保存/// </summary>/// <param name="filename">文件路径</param>/// <param name="o">对象</param>public static bool SaveAsXML(string fileName, object o){try{using (FileStream fs = File.Create(fileName)){XmlSerializer sr = new XmlSerializer(o.GetType());XmlSerializerNamespaces ns = new XmlSerializerNamespaces();ns.Add(string.Empty, string.Empty); //去除根节点的名空间sr.Serialize(fs, o, ns);fs.Close();}return true;}catch (Exception e){throw new Exception($"保存XML异常: {e.Message} 堆栈信息: {e.StackTrace}");}}private static T LoadFromXML<T>(Stream stream){T o = default(T);XmlSerializer sr = new XmlSerializer(typeof(T));o = (T)sr.Deserialize(stream);return o;} }
}
这篇关于关于C#读写XML的公用类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!