jmc
jmc

Reputation: 1729

C#: modify web.config at runtime

I have an entry in my <appSettings> section which contains my connection string. By default, it looks for the file on the root of the C: drive.

  <appSettings>
      <add key="EnvironmentFile" value="C:\environment.extension" />
  </appSettings>

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

value="~/environment.extension"

Default.aspx:

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
        }
}

In debug mode, it does modify my web.config 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?

Upvotes: 0

Views: 2400

Answers (1)

Mashton
Mashton

Reputation: 6415

Yes, there is another way of doing this.

If you right click on your Web.Config in Visual Studio you'll see an option to 'Add Config Transform'. This allows you to create transformations for your various configurations. The newly added Web.XXX.config files will have some examples of how to transform your entries, but a simple example would be:

In your base Web.Config:

  <appSettings>
      <add key="Mode" value="Development" />
  </appSettings>

And then in a WebConfig.LiveRelease.config file you might have this:

<appSettings>
    <add key="Mode" value="Live" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>

Upvotes: 0

Related Questions