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. MyBatis模糊查询的三种拼接方式

    1. sql中字符串拼接 SELECT * FROM tableName WHERE name LIKE CONCAT(CONCAT('%', #{text}), '%'); 2. 使用 ${...} ...

  2. C#中委托和代理的深刻理解(转载)

    在写代码的过程中遇到了一个问题,就是" .net CallbackOnCollectedDelegate 垃圾回收问题. " 使用全局钩子的时候出现: globalKeyboard ...

  3. linux系统之-vi编辑器

    在linux系统使用中,掌握熟练的vi编辑器,可以提高linux工作效率.那么vi编辑器的使用方法有哪些呢? vi编辑器可在绝大部分linux发行版中使用. Vi编辑器的作用:创建或修改文件:维护li ...

  4. linux安装python并安装pip

    因为最近要在linux环境下进行python编程,所以就试着去安装了一下,但是网上关于python以及pip的安装说实话有点混乱,所以我今天就把前辈的经验再次总结一下,希望可以给大家提供帮助. pyt ...

  5. 转译符,re模块,random模块

    一, 转译符 1.python 中的转译符 正则表达式中的内容在Python中就是字符串 ' \n ' : \ 转移符赋予了这个n一个特殊意义,表示一个换行符 ' \ \ n' :  \ \  表示取 ...

  6. MySQL server has gone away报错原因分析及解决办法

    原因1. MySQL 服务宕了 判断是否属于这个原因的方法很简单,执行以下命令,查看mysql的运行时长 $ mysql -uroot -p -e "show global status l ...

  7. 前端面试题目汇总摘录(JS 基础篇 —— 2018.11.02更新)

    温故而知新,保持空杯心态 JS 基础 JavaScript 的 typeof 返回那些数据类型 object number function boolean undefined string type ...

  8. ORACLE中order by造成分页不正确原因分析

     工作中遇到的问题: 为调用方提供一个分页接口时,调用方一直反应有部分数据取不到,且取到的数据有重复的内容,于是我按以下步骤排查了下错误. 1.检查分页页码生成规则是否正确. 2.检查SQL语句是否正 ...

  9. 设计模式——模版方法模式详解(论沉迷LOL对学生的危害)

    .  实例介绍 在本例中,我们使用一个常见的场景,我们每个人都上了很多年学,中学大学硕士,有的人天生就是个天才,中学毕业就会微积分,因此得了诺贝尔数学奖:也有的人在大学里学了很多东西,过得很充实很满意 ...

  10. kill -9 vs killall

    kill Linux中的kill命令用来终止指定的进程(terminate a process)的运行,是Linux下进程管理的常用命令.通常,终止一个前台进程可以使用Ctrl+C键,但是,对于一个后 ...