public void saveValue(string Name, string Value)
{
ConfigurationManager.AppSettings.Set(Name, Value);
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings[Name].Value = Value;
config.Save(ConfigurationSaveMode.Modified);
config = null;
}
用上面的函數總是等到程序運行結束,才將數據保存進去。
所以我們換了一種方式,以xml的方式進行保存及讀取。直接上代碼。
public static void SetAppConfig(string appKey, string appValue)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
var xNode = xDoc.SelectSingleNode("//appSettings");
var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
if (xElem != null) xElem.SetAttribute("value", appValue);
else
{
var xNewElem = xDoc.CreateElement("add");
xNewElem.SetAttribute("key", appKey);
xNewElem.SetAttribute("value", appValue);
xNode.AppendChild(xNewElem);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
public static string GetAppConfig(string appKey)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
var xNode = xDoc.SelectSingleNode("//appSettings");
var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
if (xElem != null)
{
return xElem.Attributes["value"].Value;
}
return string.Empty;
}
使用方式
設置
SetAppConfig("SourceDBIP", txtSourceAddress.Text.Trim());
讀取
Setting.GetAppConfig("SourceDBIP")
