有时候项目可能会有特殊要求,需要能够修改App.Config实现对应用程序的配置,但是*. Settings文件的便捷性又实在不忍抛弃,于是有了这篇文章.此次PLC模拟器开发中刚好用到,帮同事写了一下.其实很简单,就是用反射获取类的属性值,并更新到XML文件中去.直接上代码:

public Settings()
{
this.SettingsSaving += this.SettingsSavingEventHandler;
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
{
string configFileName = Application.ExecutablePath + ".config";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(configFileName);
string configString = @"configuration/userSettings/Properties.Settings/setting[@name='{0}']/value";
PropertyInfo[] configNodes = Properties.Settings.Default.GetType().GetProperties();
System.Xml.XmlNode configNode;
for (int i = 0; i < configNodes.Length; i++)
{
configNode = doc.SelectSingleNode(string.Format(configString, configNodes[i].Name));
if (configNode != null)
{
configNode.InnerText = Convert.ToString(configNodes[i].GetValue(Properties.Settings.Default, null));
}
}
doc.Save(configFileName);
}


需要注意的是在Main函数中需要Properties.Settings.Default.Reset(),以加载App.Config内容

Back