TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Add or update Connection String at Runtime in ASP.Net using C#
Ramasagar Pulidindi
Jun 19
2014
Code
2.1
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
private
void
ModifyUpdateConnectionString(
string
name)
{
bool
isNew =
false
;
string
path = Server.MapPath(
"~/Web.Config"
);
XmlDocument doc =
new
XmlDocument();
doc.Load(path);
XmlNodeList list = doc.DocumentElement.SelectNodes(
string
.Format(
"connectionStrings/add[@name='{0}']"
, name));
XmlNode node;
isNew = list.Count == 0;
if
(isNew)
{
node = doc.CreateNode(XmlNodeType.Element,
"add"
,
null
);
XmlAttribute attribute = doc.CreateAttribute(
"name"
);
attribute.Value = name;
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute(
"connectionString"
);
attribute.Value =
""
;
node.Attributes.Append(attribute);
attribute = doc.CreateAttribute(
"providerName"
);
attribute.Value =
"System.Data.SqlClient"
;
node.Attributes.Append(attribute);
}
else
{
node = list[0];
}
string
conString = node.Attributes[
"connectionString"
].Value;
SqlConnectionStringBuilder conStringBuilder =
new
SqlConnectionStringBuilder(connString);
conStringBuilder.InitialCatalog =
"SampleDB"
;
conStringBuilder.DataSource =
"myserver"
;
conStringBuilder.IntegratedSecurity =
false
;
conStringBuilder.UserID =
"sample"
;
conStringBuilder.Password =
"12345"
;
node.Attributes[
"connectionString"
].Value = conStringBuilder.ConnectionString;
if
(isNew)
{
doc.DocumentElement.SelectNodes(
"connectionStrings"
)[0].AppendChild(node);
}
doc.Save(path);
}
Modify connection string at runtime