title: C#: modify web.config at runtime
body: <p>I have an entry in my <code>&lt;appSettings&gt;</code> section which contains my connection string. By default, it looks for the file on the root of the <code>C:</code> drive.</p>
  
  <pre><code>  &lt;appSettings&gt;
        &lt;add key="EnvironmentFile" value="C:\environment.extension" /&gt;
    &lt;/appSettings&gt;
  </code></pre>
  
  <p>I need to modify the value of the entry programmatically since the app will be deployed to a different server (Appharbor), which I don't have access to the C drive. I moved the environment file to the root of the app directory which means I need to modify the appSettings value for EnvironmentFile. Here's what I have tried so far, I have resorted to the following since I can't put relative values on web.config such as </p>
  
  <pre><code>value="~/environment.extension"
  </code></pre>
  
  <p><code>Default.aspx</code>:</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
          if(ConfigurationManager.AppSettings["EnvironmentFile"] == null)
          {
              Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
              config.AppSettings.Settings.Add("EnvironmentFile", AppDomain.CurrentDomain.BaseDirectory + @"environment.extension");
  
              config.Save(ConfigurationSaveMode.Minimal);
              ConfigurationManager.RefreshSection("appSettings");
          }
  
          if (IsPostBack == false)
          {
              //--some business logic here that gets data from the database
          }
  }
  </code></pre>
  
  <p>In debug mode, it does modify my <code>web.config</code> but throws an exception since it is already executing the code on my if block. Are there other ways to do this such that I have different configuration for debug and release?</p>