简体   繁体   English

C#:在运行时修改 web.config

[英]C#: modify web.config at runtime

I have an entry in my <appSettings> section which contains my connection string.我的<appSettings>部分中有一个条目,其中包含我的连接字符串。 By default, it looks for the file on the root of the C: drive.默认情况下,它会在C:驱动器的根目录中查找文件。

  <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.我需要以编程方式修改条目的值,因为应用程序将部署到不同的服务器 (Appharbor),我无法访问 C 驱动器。 I moved the environment file to the root of the app directory which means I need to modify the appSettings value for EnvironmentFile.我将环境文件移动到应用程序目录的根目录,这意味着我需要修改 EnvironmentFile 的 appSettings 值。 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这是我到目前为止所尝试的,因为我无法在 web.config 上放置相对值,所以我采用了以下方法,例如

value="~/environment.extension"

Default.aspx : 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.在调试模式下,它确实修改了我的web.config但抛出了一个异常,因为它已经在我的 if 块上执行代码。 Are there other ways to do this such that I have different configuration for debug and release?是否有其他方法可以做到这一点,以便我对调试和发布有不同的配置?

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'.如果您在 Visual Studio 中右键单击您的Web.Config ,您将看到“添加配置转换”选项。 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:新添加的Web.XXX.config files将包含一些关于如何转换条目的示例,但一个简单的示例是:

In your base Web.Config:在您的基本 Web.Config 中:

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

And then in a WebConfig.LiveRelease.config file you might have this:然后在 WebConfig.LiveRelease.config 文件中,你可能有这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM