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. [NOI2015]程序自动分析(并查集)

    题目描述 在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足. 考虑一个约束满足问题的简化版本:假设x1,x2,x3...代表程序中出现的变量,给定n个形如xi=xj或xi≠xj的变 ...

  2. linux基础指令以及权限管理

    基础指令 #打印字符串 echo hello linux #将file1 和 file2粘合在一起,打印到标准输出流 cat file1 file2 标准输入输出 标准输入,stdin,即键盘.鼠标输 ...

  3. Docker 运行MangoDB

    1.Docker运行MangoDB镜像 #创建挂载目录 cd /opt/docker_cfg mkdir -vp mongo/db #获取mongodb镜像 [root@localhost xiaog ...

  4. 配置Echarts大全

    由于项目中需要用到Echarts,最近研究了一个星期.网上的教程也挺多的.磕磕碰碰的,难找到合适的例子.都说的马马虎虎.不废话了.开始. 这种上下排列的... 还有这种地图的.(如下) 还有就是配置的 ...

  5. ubuntu如何设置Python的版本

    Ubuntu默认已经安装了Python的版本了,不过是Python2的版本. 我们安装好Python3想把他切换为系统默认的版本. sudo update-alternatives --config ...

  6. Python起源与发展

    Python的创始人为吉多*范罗苏姆(Gudio van Rossum) 1.1989年的圣诞节期间,吉多*范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的解释程序,作为ABC语言的一种继承. 2. ...

  7. Java : java基础(4) 线程

    java开启多线程的方式,第一种是新建一个Thread的子类,然后重写它的run()方法就可以,调用类的对象的start()方法,jvm就会新开一个线程执行run()方法. 第二种是类实现Runabl ...

  8. 002---Linux系统目录结构

    Linux系统目录结构 一切从根(/)开始,一切皆文件. /bin:存放常用的可执行文件 /sbin:存放常用的可执行文件 家目录:存放用户自己的文件或目录 root用户:/root 普通用户:/ho ...

  9. centos配置npm全局安装

    使用-g全局安装在服务器需要配置,下面看看配置方法 配置全局安装路径和缓存路径 cd /usr/local/nodejs mkdir node_global mkdir node_cache npm ...

  10. java stream 处理分组后取每组最大

    有一个需求功能:先按照某一字段分组,再按照另外字段获取最大的那个 Map<String, HitRuleConfig> configMap = configList.parallelStr ...