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

winform程序读取和改写配置文件App.config元素的值

2015-11-05 11:09 246 查看
public string GetAppConfig(string key)
{
string value="";
XmlDocument doc = new XmlDocument();
doc.Load("config.xml");    //加载Xml文件
XmlElement rootElem = doc.DocumentElement;   //获取根节点
XmlNodeList personNodes = rootElem.GetElementsByTagName("add"); //获取person子节点集合
foreach (XmlNode node in personNodes)
{
string strName = ((XmlElement)node).GetAttribute("key");
if (strName == key)
{
value = ((XmlElement)node).GetAttribute("value");
break;
}
}
return value;
}


  

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<!-- 连接时间-->
<add key="CommandTimeout" value="300" />
</appSettings>
</configuration>


写:

public static void SetValue(string AppKey, string AppValue)
{
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

System.Xml.XmlNode xNode;
System.Xml.XmlElement xElem1;
System.Xml.XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");

xElem1 = (System.Xml.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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: