title: Modify programmatically connection string in the app.config before start service
body: <p>I have a problem with programmatically change connection string in the app.config file.
  In overriden OnStart method I want to change app.config file(only connection string)
  At this moment I have this:</p>
  
  <pre><code> private static void ChangeConnectionString(string newDatasource)
      {
          try
          {
              XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
              var query = from p in doc.Descendants("connectionStrings").Descendants()
                           select p;
              foreach (var child in query)
              {
                  foreach (var atr in child.Attributes())
                  {
                      if (atr.Name.LocalName == "name" &amp;&amp; atr.Value == "UniversityEntities" &amp;&amp;
                          atr.NextAttribute != null &amp;&amp; atr.NextAttribute.Name == "connectionString")
                      {
                          SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
                          connectionStringBuilder.DataSource = newDatasource;
                          connectionStringBuilder.InitialCatalog = "UniversityDB";
                          connectionStringBuilder.IntegratedSecurity = true;
  
                          EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(atr.NextAttribute.Value);
                          entityBuilder.ProviderConnectionString = connectionStringBuilder.ToString();
                          atr.NextAttribute.Value = entityBuilder.ToString();
  
                      }
                  }
  
              }
              doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
              ConfigurationManager.RefreshSection("connectionString");
          }
          catch (Exception x)
          {
          }
      }
  </code></pre>