上位机软件需要监控属性值被修改的情况,简单方法实例:
准备工作:引用log4net,编辑App.config的setting节点,填入key-value,当对应的key的value被修改时,log记录修改前的值和修改后的值。
实例:appSettings填入属性user和password
<?xml version="1.0" encoding="utf-8" ?>
<configuration><configSections><section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /></configSections><log4net configSource="log4net.config" /><appSettings><!--user--><add key="name" value="xu"/><!--password--><add key="password" value="pw123456"/></appSettings>
</configuration>
2. 在类SystemConfig.cs中创建name和password的变量并重写get和set(记录变更日志)
namespace Demo_ConfigurationManager
{public static class SystemConfig{private static readonly ILog log = LogManager.GetLogger("Demo_ConfigurationManager");public static bool LoadSystemConfig(){Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);m_strName = config.AppSettings.Settings["name"].Value;m_strPassword = config.AppSettings.Settings["password"].Value;log.Info("LoadSystemConfig success");return true;}public static bool SaveSystemConfig(){Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);config.AppSettings.Settings["name"].Value = m_strName;config.AppSettings.Settings["password"].Value = m_strPassword;config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("appSettings");log.Info("SaveSystemConfig success");return true;}private static string _name = "";public static string m_strName{get{return _name;}set{if(_name != "" && _name != value){log.Info(string.Format("user property changed from {0}->{1}", _name, value));}_name = value;}}private static string _password = "";public static string m_strPassword{get{return _password;}set{if(_password != "" && _password != value){log.Info(string.Format("passwrod property changed from {0}->{1}", _password, value));}_password = value;}}}
}