簡體   English   中英

如何在.NET應用程序中使用自定義配置文件或app.config

[英]How to use custom configuration file or app.config in .NET application

我有MVC5 .NET 4.6.1 C#Web應用程序,我想創建一個與web.config分開的自定義配置文件,以存儲我的應用程序使用的某些設置。

我試圖按照這篇文章https://support.microsoft.com/en-us/kb/815786

但是我在app.config中設置的項目:

<?xml version="1.0"?>
<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.6.1" />
      <httpRuntime targetFramework="4.6.1" />
    </system.web>
  <appSettings>
      <add key="Key0" value="0" />
      <add key="Key1" value="1" />
      <add key="Key2" value="2" />
   </appSettings>

</configuration>

在我的應用程序中看不到,例如。 它們為空:

string attr = ConfigurationManager.AppSettings["Key0"];

為什么不起作用? 我想念什么嗎?

另外,我想創建一個自定義的配置文件,例如。 mycustom.config定義我的全局應用程序設置。

編輯

我使用的解決方案

關注此帖子https://social.msdn.microsoft.com/Forums/vstudio/en-US/11e6d326-c32c-46b1-a9a2-1fbef96f33ee/howto-custom-configuration-files?forum=netfxbcl

在web.config中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
       <configSections>
              <section name="newAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
       </configSections>
       <newAppSettings file="C:\mycustom.config"/>
</configuration>

然后mycustom.config

<?xml version="1.0" encoding="utf-8" ?>
<newAppSettings>
       <add key="OurKey" value="OurValue"/>
</newAppSettings>

並讀取值:

System.Collections.Specialized.NameValueCollection newAppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("newAppSettings");
string key = Convert.ToDateTime(newAppSettings["OurKey"]);

您可以將單獨的配置文件用於連接字符串和應用程序設置:

<appSettings configSource="appSettings.config" />
<connectionStrings configSource="connectionStrings.config"/>

appSettings.config文件

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
    <add key="Setting1" value="App setting 1" />
</appSettings>

connectionStrings.config文件

<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
    <add name="MyConnStr1" connectionString="My connection string" />
</connectionStrings>

用法與以前相同:

var setting1 = ConfigurationManager.AppSettings["Setting1"];
var connString1 = ConfigurationManager.ConnectionStrings["MyConnStr1"].ConnectionString;
            //Helps to open the Root level web.config file.
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");

            //Modifying the AppKey from AppValue to AppValue1
            webConfigApp.AppSettings.Settings["AppKey"].Value = "AppValue1";



<appSettings>
    <add key="AppKey" value="AppValue"/>
  </appSettings>

暫無
暫無

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

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