【发布时间】:2016-04-28 19:49:14
【问题描述】:
我有 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 来定义我的全局应用设置。
编辑
我使用的解决方案
在 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"]);
【问题讨论】:
标签: c# .net configuration app-config configuration-files