Kev*_*ger 17 .net c# app-config
我想从名为MyAssembly.dll.config的程序集配置文件中检索AppSetting项.这是配置文件的示例:
<configuration>
<appSettings>
<add key="MyKey" value="MyVal"/>
</appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
这是检索它的代码:
var myKey = ConfigurationManager.AppSettings["MyKey"];
Run Code Online (Sandbox Code Playgroud)
mar*_*c_s 23
使用OpenMappedExeConfiguration它会返回一个"配置"对象,您可以使用该对象查看类库的配置(并且那里存在的设置将覆盖主应用程序配置中相同名称的设置):
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "ConfigLibrary.config";
Configuration libConfig = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
AppSettingsSection section = (libConfig.GetSection("appSettings") as AppSettingsSection);
value = section.Settings["Test"].Value;
Run Code Online (Sandbox Code Playgroud)
但是仍然可以通过ConfigurationManager静态类访问那些主应用程序配置所特有但在类库自己的配置中不存在的设置:
string serial = ConfigurationManager.AppSettings ["Serial"];
这仍然有效 - 类库的配置只隐藏其配置文件中的那些设置; 另外,您还需要使用" libConfig实例"来访问类库自己的配置设置.
两个世界(主app.config,classlibrary.config)可以完全和非常愉快地共存 - 根本不存在问题!
渣
小智 6
var appSettings = ConfigurationManager.OpenExeConfiguration((Assembly.GetAssembly(typeof(MYASSEMBLY))).Location).AppSettings;
Run Code Online (Sandbox Code Playgroud)
然后你可以像上面那样做.