如何修改和读取app.config文件?网上找的格式和这个都不一样,有劳前辈了!
读取IS_SQLConnString和(Local)
写入连接字符串
请指点!
app.config文件代码如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="IS_SQLConnString" connectionString="server=(Local);database=InformationSystem_2012;uid=sa;pwd=qjw159" />
<add name="other" connectionString="其他数据库的连接字符串" />
</connectionStrings>
</configuration>
------解决方案--------------------ConfigurationManager.ConnectionStrings["IS_SQLConnString"].ConnectionString
需要引入System.Configuration
------解决方案--------------------用XmlElement element=xmlDoc.SelectSingleNode(@"/configuration/connectionStrings/add[@name='IS_SQLConnString']") as XmlElement;
获取第一个连接字符串的add元素,用element.SetAttribute方法修改其属性的值。
------解决方案--------------------
C# code
public static void SetValue(string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
//加载app.config
xDoc.Load("..\\..\\app.config");
XmlNode xNode = xDoc.SelectSingleNode("//connectionStrings");
XmlElement oldElement = (XmlElement)xNode.SelectSingleNode("//add[@name='" + AppKey + "']");
if (oldElement != null)
{
oldElement.SetAttribute("connectionString", AppValue);
}
else
{
XmlElement newElement = xDoc.CreateElement("add");
newElement.SetAttribute("name", AppKey);
newElement.SetAttribute("connectionString", AppValue);
xNode.AppendChild(newElement);
}
xDoc.Save("..\\..\\app.config");
}