How do I retrieve AppSettings from the assembly config file?

a 夏天 提交于 2019-11-30 05:56:36

问题


I would like to retrieve the AppSetting key from the assembly config file called: MyAssembly.dll.config. Here's a sample of the config file:

<configuration>
    <appSettings>
        <add key="MyKey" value="MyVal"/>
    </appSettings>
</configuration>

Here's the code to retrieve it:

var myKey = ConfigurationManager.AppSettings["MyKey"];

回答1:


Using the OpenMappedExeConfiguration gives you back a "Configuration" object which you can use to peek into the class library's config (and the settings that exist there will override the ones by the same name in the main app's config):

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;

But those settings that are unique to the main app's config and do not exist in the class library's own config are still accessible via the ConfigurationManager static class:

string serial = ConfigurationManager.AppSettings["Serial"];

That still works - the class library's config only hides those settings that are inside its config file; plus you need to use the "libConfig instance to get access to the class library's own config settings, too .

The two worlds (main app.config, classlibrary.config) can totally and very happily co-exist - not a problem there at all!

Marc




回答2:


var appSettings = ConfigurationManager.OpenExeConfiguration((Assembly.GetAssembly(typeof(MYASSEMBLY))).Location).AppSettings;

then you can do as above.




回答3:


You can also open it up as an XmlDocument and navigate the document with Xpath. THen there is always LinqToXml




回答4:


var uri = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase));
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(uri.LocalPath, "MyAssembly.dll.config") };
var assemblyConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 



回答5:


Using System.Configuration
Public Shared Function AppDomainConfiguration() As Configuration
  Dim fileMap As New ExeConfigurationFileMap
  fileMap.ExeConfigFilename = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
  Return ConfigurationManager.OpenMappedExeConfiguration(fileMap,Configuration.ConfigurationUserLevel.None)
End Function


来源:https://stackoverflow.com/questions/1682054/how-do-i-retrieve-appsettings-from-the-assembly-config-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!