日期:2014-05-20  浏览次数:21056 次

Windows程序控件属性与配置文件的<appSettings>节中的值映射问题
将windows应用程序配置文件的 <appSettings> 节中的值映射到控件的属性,
在控件属性更改后,怎么保存到配置文件中啊?
我以前用修改XML文件保存,这样太啰唆了,有没有更好的办法?

------解决方案--------------------
用这个类:
using System;
using System.Xml;
using System.Windows.Forms;

namespace Common
{
/// <summary>
/// 模块名称: 读写系统配置类
/// 编写日期: 2005-12-01
/// </summary>
public class AppConfig
{
public static bool UpdateConfig(string strKey, string strValue)
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Application.ExecutablePath + ".config ");
XmlNode node = doc.SelectSingleNode(@ "//add[@key= ' " + strKey + " '] ");
XmlElement ele = (XmlElement)node;
ele.SetAttribute( "value ", strValue);
doc.Save(Application.ExecutablePath + ".config ");
}
catch
{
return false;
}
return true;
}
public AppConfig()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static string GetConfig(string strKey)
{
//return System.Configuration.ConfigurationManager.AppSettings[strKey];
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Application.ExecutablePath + ".config ");
XmlNode node = doc.SelectSingleNode(@ "//add[@key= ' " + strKey + " '] ");
XmlElement ele = (XmlElement)node;
return ele.GetAttribute( "value ");
}
catch
{
return string.Empty;
}
}
}
}

------解决方案--------------------
那是当然的,要重启应用程序才能取得更改后的值。所以动态改app.config没啥意义,如果要看到即时的修改结果,可以用注册表存配置信息。

------解决方案--------------------
如果是2003,本质上还是需要通过修改app.config的方式来处理,如果是2005,
增加了Settings.setting设置文件,可以对用户级别的配置文件进行直接修改。
http://www.microsoft.com/china/msdn/library/langtool/vcsharp/SettingsCSRL.mspx?mfr=true