01.
private
void
AddUpdateConnectionString(
string
name)
02.
{
03.
bool
isNew =
false
;
04.
string
path = Server.MapPath(
"~/Web.Config"
);
05.
XmlDocument doc =
new
XmlDocument();
06.
doc.Load(path);
07.
XmlNodeList list = doc.DocumentElement.SelectNodes(
string
.Format(
"connectionStrings/add[@name='{0}']"
, name));
08.
XmlNode node;
09.
isNew = list.Count == 0;
10.
if
(isNew)
11.
{
12.
node = doc.CreateNode(XmlNodeType.Element,
"add"
,
null
);
13.
XmlAttribute attribute = doc.CreateAttribute(
"name"
);
14.
attribute.Value = name;
15.
node.Attributes.Append(attribute);
16.
17.
attribute = doc.CreateAttribute(
"connectionString"
);
18.
attribute.Value =
""
;
19.
node.Attributes.Append(attribute);
20.
21.
attribute = doc.CreateAttribute(
"providerName"
);
22.
attribute.Value =
"System.Data.SqlClient"
;
23.
node.Attributes.Append(attribute);
24.
}
25.
else
26.
{
27.
node = list[0];
28.
}
29.
string
conString = node.Attributes[
"connectionString"
].Value;
30.
SqlConnectionStringBuilder conStringBuilder =
new
SqlConnectionStringBuilder(conString);
31.
conStringBuilder.InitialCatalog =
"TestDB"
;
32.
conStringBuilder.DataSource =
"myserver"
;
33.
conStringBuilder.IntegratedSecurity =
false
;
34.
conStringBuilder.UserID =
"test"
;
35.
conStringBuilder.Password =
"12345"
;
36.
node.Attributes[
"connectionString"
].Value = conStringBuilder.ConnectionString;
37.
if
(isNew)
38.
{
39.
doc.DocumentElement.SelectNodes(
"connectionStrings"
)[0].AppendChild(node);
40.
}
41.
doc.Save(path);
42.
}