簡體   English   中英

如何通過 app.config 變量覆蓋 settings.settings 變量

[英]How to override settings.settings variable by app.config variable

如何通過在生產環境中向 app.config 添加變量來更改(或覆蓋)settings.settings 變量?

這可能嗎?

您必須直接引用您嘗試覆蓋的 applicationSettings 並明確指定具有替換值的屬性。

<configuration>
  <!-- section definitions for all elements in <configuration> tag -->
  <configSections>
    <!-- section group, meaning: there will be a <applicationSettings> tag in you configuration-->
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <!-- defines that there will be a <appname.Properties.Settings> tag inside your <applicationSettings> tag -->
      <section name="appname.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <applicationSettings>
    <appname.Properties.Settings>
      <!-- name of the property you want to override -->
      <setting name="setting1" serializeAs="String">
        <!-- new value -->
        <value>new string value</value>
      </setting>
    </appname.Properties.Settings>
  </applicationSettings>
</configuration>

對於應用程序 scope 連接字符串值:

  <connectionStrings>
    <add name="appname.Properties.Settings.setting1" connectionString="test string" providerName="dbProvider"/>
  </connectionStrings>

這取決於 scope 的設置。 如果它的應用程序 scope 設置更改它在 app.config 中的值就足夠了。

但是,如果它是用戶 scope 設置,那么 app.config 中的值只是用於新用戶的默認值,並且每個已經使用該應用程序的用戶都將當前使用的值存儲在單獨的文件 user.config 中,所以更改 app.config 中的值對已經運行過一次應用程序的用戶沒有影響。

因此,更改用戶 scope 設置的值可能是一項麻煩的任務。 您可以查看以下答案以獲取有關更改用戶 scope 設置的更多信息:

更改用戶 Scope 應用程序設置

為生產和您使用不同的配置文件。 基本上在生產環境中,您將在 RELEASE 中進行編譯,因此如果您使用 Visual Studio 進行編譯,請使用構建后事件來復制 RELEASE 配置文件,以防您為生產環境准備構建。

我更喜歡這個而不是從代碼中更改它,因為其他人更容易看到配置文件中的差異,然后深入代碼以查找所有if/else內容。

僅通過代碼:

例如

 if (bool.Parse(ConfigurationManager.AppSettings["overridethis"].ToString()))
 {
     //use overridden value
 }

但是,如果您的問題是在不同的環境中維護不同的配置值,那么我會改用 AppSettings。

然后,您可以使用開發人員覆蓋文件。

 <appSettings file="..\user.config">

http://www.compiledthoughts.com/2005/03/overriding-webconfig-app-settings-with.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM