
[英]How to use App.config in WPF application for log4net configuration
[英]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定义我的全局应用程序设置。
编辑
我使用的解决方案
在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.