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"];
To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below. When we implement the code given above, we get the output, as shown below.
You can access the config values through ConfigurationSettings. AppSettings["Your Key"].
The system settings include appSettings keys and other settings, such as a connection string placed in appropriate sections of the project's web. config file. AppSettings keys are stored in the /configuration/appSettings section.
The <appSettings> element stores custom application configuration information, such as database connection strings, file paths, XML Web service URLs, or any other custom configuration information for an application.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With