Change connection string from C#


Ever want to change the connection string of the database from C# code in your application than your are at right place.
The below code snippet in C# exactly does that. Changing the connection string in your web.config or app.config file programmatically or with C# code.

Code Snippet
  1. private void UpdateConnectionString(string ConfigPath)
  2. {
  3.    XmlDocument xmlDocument = new XmlDocument();
  4.    xmlDocument.Load(ConfigPath);
  5.    XmlNode parentNode = xmlDocument.DocumentElement;
  6.    if (parentNode.Name == "connectionStrings")
  7.    {
  8.       foreach (XmlNode childNode in parentNode.ChildNodes)
  9.       {
  10.          if (childNode.Name == "add" && childNode.Attributes["name"].Value=="MySqlConnection")
  11.          {
  12.             string sqlConnectionString = childNode.Attributes["connectionString"].Value;
  13.             SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(sqlConnectionString);
  14.             sqlBuilder.InitialCatalog = "yourDatabaseName";
  15.             sqlBuilder.IntegratedSecurity = true;
  16.             sqlBuilder.Password = "";
  17.            
  18.             //Change any other attributes using the sqlBuilder object
  19.             childNode.Attributes["connectionString"].Value = sqlBuilder.ConnectionString;
  20.          }
  21.       }
  22.    }
  23.    xmlDocument.Save(ConfigPath);
  24. }


Post a Comment