需要使用name = "SqlServer"
配置文件就像xml一样,而不是来自我的项目
<connectionStrings>
<add name="SqlServer"
connectionString="Data Source=192.168.1.1; Initial Catalog=s; Application Name=s; MultipleActiveResultSets = true; Pooling=True; User ID=1111;Password=1111;" />
<add name="SqlServer_WinAuthentication"
connectionString="Data Source=.; Initial Catalog=MeterShop; Integrated Security=True; Application Name=MeterShop; MultipleActiveResultSets = true; Pooling=True;" />
<add name="SqlServer_SqlAuthentication"
connectionString="Data Source=.; Initial Catalog=MeterShop; User ID=1; Password=1; Application Name=1; MultipleActiveResultSets = true; Pooling=True;" />
</connectionStrings>
答案 0 :(得分:0)
使用XML Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication70
{
class Program
{
static void Main(string[] args)
{
string xml =
"<connectionStrings>" +
"<add name=\"SqlServer\"" +
" connectionString=\"Data Source=192.168.1.1; Initial Catalog=s; Application Name=s; MultipleActiveResultSets = true; Pooling=True; User ID=1111;Password=1111;\" />" +
"<add name=\"SqlServer_WinAuthentication\"" +
" connectionString=\"Data Source=.; Initial Catalog=MeterShop; Integrated Security=True; Application Name=MeterShop; MultipleActiveResultSets = true; Pooling=True;\" />" +
"<add name=\"SqlServer_SqlAuthentication\"" +
" connectionString=\"Data Source=.; Initial Catalog=MeterShop; User ID=1; Password=1; Application Name=1; MultipleActiveResultSets = true; Pooling=True;\" />" +
"</connectionStrings>";
XElement connectionStrings = XElement.Parse(xml);
List<XAttribute> names = connectionStrings.Descendants("add").Select(x => x.Attribute("name")).ToList();
foreach (XAttribute name in names)
{
name.Value = "123";
}
}
}
}
答案 1 :(得分:0)
有很多方法可以实现这一点,我更喜欢Linq
到Xml
XDocument doc = XDocument.Parse(s);
var target = doc.Descendants("connectionStrings")
.SingleOrDefault(e => e.Element("add").Attribute("name").Value == "SqlServer");
获得目标元素后,您可以更新该值。
target.Element("add").Attribute("name").Value = "any thing you want";
doc.Save("filename"); // Save the file after your changes.
工作Example