您的位置:首页 > 移动开发

winform中app.config的动态读写操作

2010-04-13 14:08 399 查看
在winform中使用程序动态读取和修改App.config里面的appSettings当中的Value值,解决winform中没有的修改和修改后不能及时取得其值的问题:
//写操作
public static void SetValue(string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
//获取可执行文件的路径和名称
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
//读操作
public string GetConfigValue(string appKey)
{
XmlDocument xDoc = new XmlDocument();
try
{
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNode xNode;
XmlElement xElem;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
if (xElem != null)
return xElem.GetAttribute("value");
else
return "";
}
catch (Exception)
{
return "";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: