赞
踩
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;
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。