title: Modifying config sections in App.config either at runtime or install time
body: <p>I have an WinForms application that is deployed using Visual Studio 2008's publish (ClickOnce) system. Within the application's <code>app.config</code> file I have a config section that is required by a third party component that has the form:</p>
  
  <pre><code>&lt;section name="thirdPartySection"
  type="System.Configuration.NameValueSectionHandler" /&gt;
  </code></pre>
  
  <p>The section is thus not in the appSettings and looks like:</p>
  
  <pre><code>&lt;thirdPartySection &gt;
    &lt;add key="someKey" value="someValue" /&gt;
  &lt;/thirdPartySection &gt;
  </code></pre>
  
  <p>I understand that the key/value pairs are a NameValueCollection. The problem I face is that I wish to <em>change</em> the value either a deployment time or at runtime (either is fine with me) so that <code>someValue</code> will be <code>someOtherValue</code> based on the environment installed in.</p>
  
  <p>Currently I make some other config changes at runtime, but those are in the <code>AppSettings</code> section, and thus easy to get at. I have found many references in my search for a solution, but they seem to rely on the section having a custom class, not the NameValueCollection that I'm faced with.</p>
  
  <p>Does anyone know the best way to modify this data? A runtime change with a ConfigurationManager.RefreshSection() would be more in line with my current code, but I'm open to suggestions during the install phase as well.</p>
  
  <p><strong>Edit: This works at runtime.</strong> This is how I was handling the old configuration overrides.</p>
  
  <pre><code>Configuration config = ConfigurationManager.OpenExeConfiguration(
      ConfigurationUserLevel.None);
  
  config.AppSettings.Settings["Main.ConnectionString"].Value = 
      PolicyTrackerInfo.ConnectionString;
  
  config.AppSettings.Settings["Main.linq"].Value = 
      PolicyTrackerInfo.LinqConnectionString;
  
  
  config.Save(ConfigurationSaveMode.Modified);
  
  ConfigurationManager.RefreshSection("appSettings");
  </code></pre>
  
  <p>My attempt to do the same for another section:</p>
  
  <pre><code>string overwriteXml = config.GetSection("thirdPartySection")
      .SectionInformation.GetRawXml();
  
  XmlDocument xml = new XmlDocument();
  xml.LoadXml(overwriteXml);
  XmlNode node = xml.SelectSingleNode("thirdPartySection/add");
  node.Attributes["value"].Value = PolicyTrackerInfo.OverwriteString;
  </code></pre>
  
  <p>So far, so good. However, I don't see a method that allows me to replace the old XML with my modified data. <em>Is it possible at runtime?</em> </p>
  
  <p>As an aside: I tried modifying the app.config.deploy file by hand. That just gives me a validation error as the modification is detected by the installer and it refuses to proceed. I really like the auto deploy, and the prior override worked great. </p>