Winform及WPF项目中经常会用到类似SystemSetting.xml等类似的文件用于保存CLIENT的数据,比如登录过的用户名或密码以及其他设置。所以就想到一个解决方法,可以用到所有有此需求的项目中去,避免重复写代码。

1.创建一个Attribute类,用于指定属性在XML文件中的Path

  public class NodePathAttribute : Attribute
{
public string NodePath
{
get;
set;
} public string DefaultValue
{
get;
set;
} public NodePathAttribute(string nodePath)
{
NodePath = nodePath;
} public NodePathAttribute(string nodePath,string defaultValue)
:this(nodePath)
{
DefaultValue = defaultValue;
}
}

2.SystemSetting类用于定义要读取和保存的属性,SystemSetting继续XMLSettingBase

 namespace ConsoleApplication2
{
public class SystemSetting : XMLSettingBase
{
#region Property #region HostLocationSetting /// <summary>
/// host wcf service location
/// </summary>
[NodePath("/Settings/HostLocationSetting/HostLocation")]
public string HostLocation { get; set; } /// <summary>
/// host wcf service port
/// </summary>
[NodePath("/Settings/HostLocationSetting/HostPort")]
public int? HostPort { get; set; } #endregion #region SystemFolderSetting /// <summary>
/// NiceLable sdk niceengine5wr.dll path
/// </summary>
[NodePath("/Settings/SystemFolderSetting/NiceEngineFolderPath")]
public string NiceEngineFolderPath
{
get;
set;
} #endregion #region SearchSetting /// <summary>
/// Main program
/// </summary>
[NodePath("/Settings/SearchSetting/MainProgram")]
public string MainProgram
{
get;
set;
} /// <summary>
/// Sub program
/// </summary>
[NodePath("/Settings/SearchSetting/SubProgram")]
public string SubProgram
{
get;
set;
} /// <summary>
/// Get/Set Date Range to auto setting and search condition
/// </summary>
[NodePath("/Settings/SearchSetting/DateRange")]
public int? DateRange
{
get;
set;
} /// <summary>
/// Get/Set Date Range unit 0:days;1:weeks;2:months;3:years
/// </summary>
[NodePath("/Settings/SearchSetting/DateRangeUnit")]
public int? DateRangeUnit
{
get;
set;
} /// <summary>
/// search status
/// </summary>
[NodePath("/Settings/SearchSetting/Status")]
public FileStatus? Status
{
get;
set;
} /// <summary>
/// Skip printed order
/// </summary>
[NodePath("/Settings/SearchSetting/SkipPrintedOrder")]
public bool? SkipPrintedOrder
{
get;
set;
} #endregion #region PrintSetting [NodePath("/Settings/PrintSetting/ReturnQCResult")]
public bool? ReturnQCResult { get; set; } [NodePath("/Settings/PrintSetting/ActualPrintQuantity")]
public bool? ActualPrintQuantity { get; set; } [NodePath("/Settings/PrintSetting/MOSeperator")]
public bool? MOSeperator { get; set; } [NodePath("/Settings/PrintSetting/SKUSeperator")]
public string SKUSeperator { get; set; } #endregion #region LoginSetting [NodePath("/Settings/LoginSetting/UserName")]
public string UserName { get; set; } [NodePath("/Settings/LoginSetting/Password")]
public string Password { get; set; } [NodePath("/Settings/LoginSetting/Language")]
public string Language { get; set; } #endregion #endregion #region Ctor public SystemSetting(string filePath)
:base(filePath)
{ } #endregion
}
}
public class XMLSettingBase
{
#region Field protected string _filePath = null;
protected XmlDocument _xmlDocument = null; public delegate void SettingChange(); #endregion #region Ctor public XMLSettingBase(string filePath)
{
_filePath = filePath;
_xmlDocument = new XmlDocument();
_xmlDocument.Load(filePath);
} #endregion #region Event public event SettingChange OnSettingChangeEvent; #endregion #region Method /// <summary>
/// init system setting
/// </summary>
public void LoadData()
{
PropertyInfo[] propertyInfoes = this.GetType().GetProperties();
if (propertyInfoes == null && propertyInfoes.Length == ) { return; } //load each setting value
foreach (var propertyInfo in propertyInfoes)
{
NodePathAttribute customerAttribute = propertyInfo.GetCustomAttribute<NodePathAttribute>(); if (customerAttribute == null) { continue; } string propertyValue = string.Empty;
if (_xmlDocument.SelectSingleNode(customerAttribute.NodePath) != null)
{
propertyValue = GetXmlNodeValue(customerAttribute.NodePath);
}
else
{
CreateNode(customerAttribute.NodePath); propertyValue = customerAttribute.DefaultValue;
} //whether need to decrypt value
EncryptAttribute encryptAttribute = propertyInfo.GetCustomAttribute<EncryptAttribute>();
if (encryptAttribute == null)
{
SetPropertyInfoValue(propertyInfo, this, propertyValue);
}
else
{
SetPropertyInfoValue(propertyInfo, this, Decrypt(propertyValue, encryptAttribute.EncryptPassword));
} } LoadExtendData();
} public virtual void LoadExtendData()
{
return;
} /// <summary>
/// save data to xml file.
/// </summary>
public void SaveData()
{
PropertyInfo[] propertyInfoes = this.GetType().GetProperties();
if (propertyInfoes == null && propertyInfoes.Length == ) { return; } //load each setting value
foreach (var propertyInfo in propertyInfoes)
{
NodePathAttribute customerAttribute = propertyInfo.GetCustomAttribute<NodePathAttribute>(); if (customerAttribute == null) { continue; } object propertyValue = propertyInfo.GetValue(this); //whether need to decrypt value
EncryptAttribute encryptAttribute = propertyInfo.GetCustomAttribute<EncryptAttribute>();
if (encryptAttribute == null)
{
SetXmlNodeValue(customerAttribute.NodePath, propertyValue != null ? propertyValue.ToString() : string.Empty);
}
else
{
SetXmlNodeValue(customerAttribute.NodePath, propertyValue != null ? Encrypt(propertyValue.ToString(), encryptAttribute.EncryptPassword) : string.Empty);
}
} _xmlDocument.Save(_filePath);
} /// <summary>
/// refresh system setting
/// </summary>
public void Refresh()
{
//save data
SaveData();
//reload the data.
LoadData();
//triggering event
if (OnSettingChangeEvent != null)
{
OnSettingChangeEvent();
}
} public string GetXmlNodeValue(string strNode)
{
try
{
XmlNode xmlNode = _xmlDocument.SelectSingleNode(strNode);
return xmlNode.InnerText;
}
catch (Exception ex)
{
throw ex;
}
} public void SetXmlNodeValue(string strNode, string value)
{
try
{
XmlNode xmlNode = _xmlDocument.SelectSingleNode(strNode);
xmlNode.InnerText = value;
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// convert the datatable to list
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private void SetPropertyInfoValue(PropertyInfo propertyInfo, object obj, object value)
{
//check value
if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
{
return;
} string strValue = value.ToString(); if (propertyInfo.PropertyType.IsEnum)
{
propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, strValue), null);
}
else
{
string propertyTypeName = propertyInfo.PropertyType.Name;
switch (propertyTypeName)
{
case "Int32":
case "Int64":
case "Int":
int intValue;
int.TryParse(strValue, out intValue);
propertyInfo.SetValue(obj, intValue, null);
break;
case "Long":
long longValue;
long.TryParse(strValue, out longValue);
propertyInfo.SetValue(obj, longValue, null);
break;
case "DateTime":
DateTime dateTime;
DateTime.TryParse(strValue, out dateTime);
propertyInfo.SetValue(obj, dateTime, null);
break;
case "Boolean":
Boolean bv = false;
if ("".Equals(value) || "true".Equals(strValue.ToLower()))
{
bv = true;
}
propertyInfo.SetValue(obj, bv, null);
break;
case "Nullable`1":
if (propertyInfo.PropertyType.GenericTypeArguments[].IsEnum)
{
propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType.GenericTypeArguments[], strValue), null);
}
else
{
switch (propertyInfo.PropertyType.GenericTypeArguments[].FullName)
{
case "System.Int32":
case "System.Int64":
case "System.Int":
int intV;
int.TryParse(strValue, out intV);
propertyInfo.SetValue(obj, intV, null);
break;
case "System.DateTime":
DateTime dtime;
DateTime.TryParse(strValue, out dtime);
propertyInfo.SetValue(obj, dtime, null);
break;
case "System.Boolean":
Boolean boolv = false;
if ("".Equals(value) || "true".Equals(strValue.ToLower()))
{
boolv = true;
}
propertyInfo.SetValue(obj, boolv, null);
break;
default:
propertyInfo.SetValue(obj, strValue, null);
break;
}
}
break;
default:
propertyInfo.SetValue(obj, strValue, null);
break;
} }
} /// <summary>
/// Decrypt text
/// </summary>
/// <param name="value"></param>
/// <param name="password"></param>
/// <returns></returns>
private string Decrypt(string value, string password)
{
Encryption encryption = new Encryption();
string outMsg = null;
//Decrypt
if (!string.IsNullOrEmpty(value))
{
encryption.DesDecrypt(value, password, out outMsg);
} return outMsg; } /// <summary>
/// Enctypr text
/// </summary>
/// <param name="value"></param>
/// <param name="password"></param>
/// <returns></returns>
private string Encrypt(string value, string password)
{
Encryption encryption = new Encryption();
string outMsg = null; if (encryption.DesEncrypt(value, password, out outMsg))
{
return outMsg;
}
else
{
return string.Empty;
} } public void CreateNode(string strNode)
{
string[] nodes = strNode.Split(new[] { @"/" }, StringSplitOptions.RemoveEmptyEntries); var tempNode = new StringBuilder();
for (int i = ; i < nodes.Length; i++)
{
string parentNodePath = tempNode.ToString(); tempNode.Append(@"/"); tempNode.Append(nodes[i]); //此节点不存在,则创建此结点
if (_xmlDocument.SelectSingleNode(tempNode.ToString()) == null)
{
XmlNode newNode = _xmlDocument.CreateElement(nodes[i]); //寻找父结点
XmlNode parentNode = _xmlDocument.SelectSingleNode(parentNodePath); if (parentNode != null)
{
parentNode.AppendChild(newNode);
}
}
} _xmlDocument.Save(_filePath);
} #endregion }

3.测试用类

 这是需要操作的文件
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<HostLocationSetting>
<HostLocation></HostLocation>
<HostPort></HostPort>
</HostLocationSetting>
<SystemFolderSetting>
<NiceEngineFolderPath></NiceEngineFolderPath>
</SystemFolderSetting>
<SearchSetting>
<MainProgram></MainProgram>
<SubProgram></SubProgram>
<Status></Status>
<SkipPrintedOrder>true</SkipPrintedOrder>
<DateRange></DateRange>
<DateRangeUnit></DateRangeUnit>
</SearchSetting>
<PrintSetting>
<ReturnQCResult>false</ReturnQCResult>
<ActualPrintQuantity></ActualPrintQuantity>
<MOSeperator>true</MOSeperator>
<SKUSeperator></SKUSeperator>
</PrintSetting>
<LoginSetting>
<UserName></UserName>
<Password></Password>
<Language></Language>
</LoginSetting> </Settings> 测试代码如下
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SystemSetting systemSetting = new SystemSetting(@"Config/SystemSetting.xml"); systemSetting.LoadData(); Console.WriteLine(systemSetting.HostLocation);
Console.WriteLine(systemSetting.Status);
Console.WriteLine(systemSetting.SkipPrintedOrder); systemSetting.HostLocation = "192.168.15.171";
systemSetting.Status = FileStatus.PARTIAL_PRINTED;
systemSetting.SkipPrintedOrder = true; systemSetting.Refresh(); systemSetting.LoadData(); Console.WriteLine(systemSetting.HostLocation);
Console.WriteLine(systemSetting.Status);
Console.WriteLine(systemSetting.SkipPrintedOrder); Console.ReadKey(); }
}
}

项目常用解决方案之SystemSetting.xml文件的修改与读取的更多相关文章

  1. .net操作xml文件(新增.修改,删除,读取) 转

    今天有个需求需要操作xml节点.突然见遗忘了许多.上网看了些资料.才整出来.脑袋真不够用.在这里把我找到的资料共享一下.方便以后使用.本文属于网摘/ 1 一.简单介绍2 using System.Xm ...

  2. .net操作xml文件(新增.修改,删除,读取)---datagridview与xml文件

    参考网址: http://www.cnblogs.com/liguanghui/archive/2011/11/10/2244199.html 很详细的,相信能给你一定的帮助.

  3. 安装时后的idea,项目不能运行,pom.xml文件不能下载到本地仓库,maven配置是正确的

    安装时后的idea,项目不能运行,pom.xml文件不能下载到本地仓库,maven配置是正确的 项目上传到svn后,同事下载项目后,没有识别出来mavn中的pom.xml文件,导致idea不能自动下载 ...

  4. 解析xml文件,修改Jenkins的配置

    最近因为服务器移动,在Jenkins中配置的一些地址之类的,都要改变,如图,我因为使用插件Sidebar Links增加一个链接地址,现在地址变了,所以在Jenkins中配置就需要改动link url ...

  5. Eclipse使用之将Git项目转为Maven项目, ( 注意: 最后没有pom.xml文件的, 要转化下 )

    Eclipse使用之将Git项目转为Maven项目(全图解) 2017年08月11日 09:24:31 阅读数:427 1.打开Eclipse,File->Import 2.Git->Pr ...

  6. 【java项目实战】dom4j解析xml文件,连接Oracle数据库

    简单介绍 dom4j是由dom4j.org出品的一个开源XML解析包.这句话太官方.我们还是看一下官方给出的解释.例如以下图: dom4j是一个易于使用的.开源的,用于解析XML,XPath和XSLT ...

  7. 创建maven web项目时,没有web.xml文件

    1.问题:创建maven项目时,选择的是创建web-app项目,但是结果配置之后,却没有web.xml文件. 2.解决办法: ------------------------------------- ...

  8. Eclipse建立Web项目,手动生成web.xml文件

    相关文章:https://blog.csdn.net/ys_code/article/details/79156188(Web项目建立,手动生成web.xml文件

  9. SpringBoot项目编译后没有xxxmapper.xml文件解决方法

    在pom.xml文件中添加如下代码 <build> <plugins> <plugin> <groupId>org.springframework.bo ...

随机推荐

  1. Zabbix——部署(DB与web一体)

    前提条件: CentOS连接网络并可以正常访问网络 DNS设置完成,可以Ping同外网域名 安装数据库为8.0版本 关闭防火墙 如果需要搭建分离式请见:DB与Web分离 &DB.web.age ...

  2. deepin系统无线网络卡死或者极慢的解决方案

    在初次安装deb或者fedara系列的桌面发行版的之后,经常会出现无线网络极慢甚至卡死的状况. 笔者在初次使用deepin系统的时候,也遇到同样的问题,很大程度上是由于没有安装对应的驱动. 下面给出对 ...

  3. Co. - Microsoft - Windows - 通过任务计划,备份本地MySQL,数据上传Linux备份服务器

    需求 客户为Windows系统,安装MySQL,需要每日备份数据库到指定目录,并且上传到公司的备份服务器(Linux). 1.使用mysqldump备份MySQL数据库,使用FTP上传到阿里云Linu ...

  4. DevOps - 项目构建 - Maven

    Maven介绍Apache Maven是一个创新的软件项目管理和综合工具.Maven提供了一个基于项目对象模型(POM)文件的新概念来管理项目的构建,可以从一个中心资料片管理项目构建,报告和文件.Ma ...

  5. 初学Node.js -环境搭建

    从毕业一直到现在都是在做前端,总感觉缺少点什么,java? PHP? .Net? 框架太多了,学起来不好掌握,听说node.js挺牛的,我决定把node.js好好的学一下.首先是环境的配置,这个配置真 ...

  6. JAVAOOP I/O

    程序的主要任务就是操作数据,通过允许程序读取文件的内容或向文件写入数据,可以使程序应用更加广泛. I/O(input/output) 在不同操作系统之下,所占的字节数也不同,一般认为 8.1.1使用F ...

  7. Centos6 Ruby 1.8.7升级至Ruby 2.3.1的方法

    本文章地址:https://www.cnblogs.com/erbiao/p/9117018.html#现在的版本 [root@hd4 /]# ruby --version ruby (-- patc ...

  8. mysql根据二进制日志恢复数据/公司事故实战经验

    根据二进制日志恢复 目的:恢复数据,根据二进制日志将数据恢复到今天任意时刻 增量恢复,回滚恢复 如果有备份好的数据,将备份好的数据导入新数据库时,会随着产生二进制日志 先准备一台初始化的数据库 mys ...

  9. ruby Logger日志

    1.logger创建 # 输出到标准输出 logger = Logger.new(STDERR) logger = Logger.new(STDOUT) # 输出到指定文件 logger = Logg ...

  10. (数据科学学习手册28)SQL server 2012中的查询语句汇总

    一.简介 数据库管理系统(DBMS)最重要的功能就是提供数据查询,即用户根据实际需求对数据进行筛选,并以特定形式进行显示.在Microsoft SQL Serve 2012 中,可以使用通用的SELE ...