Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Tip/Trick

Programatically update connectionstring using C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
7 Nov 2011CPOL 32K   11   3
Programatically update connectionstring using C#
C#
private void UpdateConnectionString(string ConfigPath)
{
   XmlDocument xmlDocument = new XmlDocument();
   xmlDocument.Load(ConfigPath);
   XmlNode parentNode = xmlDocument.DocumentElement;
   if (parentNode.Name == "connectionStrings")
   {
      foreach (XmlNode childNode in parentNode.ChildNodes)
      {
         if (childNode.Name == "add" && childNode.Attributes["name"].Value=="MySqlConnection")
         {
            string sqlConnectionString = childNode.Attributes["connectionString"].Value;
            SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(sqlConnectionString);
            sqlBuilder.InitialCatalog = "yourDatabaseName";
            sqlBuilder.IntegratedSecurity = true;
            sqlBuilder.Password = "";
           
            //Change any other attributes using the sqlBuilder object
            childNode.Attributes["connectionString"].Value = sqlBuilder.ConnectionString;
         }
      }
   }
   xmlDocument.Save(ConfigPath);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Software developer by profession, working for a service and product based organisation in India.

Career graph:
Software Programmer since 2002.
Web Developer in ASP.NET since 2004.

Interests:
I love reading the blogs and articles of technology experts. I love codeproject and stackoverflow .

I love to share knowledge and help the programmers. I appreciate if some body corrects my code or my concepts which helps me learn.

Comments and Discussions

 
GeneralJust a comment: try using SelectSingleNode and XPath to acce... Pin
PIEBALDconsult8-Nov-11 17:53
mvePIEBALDconsult8-Nov-11 17:53 
GeneralRe: nice suggestion.. will try to update my code. However, I wou... Pin
bbirajdar9-Nov-11 3:59
bbirajdar9-Nov-11 3:59 
QuestionAre you sure this will work Pin
Doubin7-Nov-11 18:32
Doubin7-Nov-11 18:32 
If you are not running the application as Administrator you may be in a for an annoying disappointment.

Changing files in the Program files and wwwroot folder needs elevated permissions.
http://doubin.blogspot.com/

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.