Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve AppSettings from the assembly config file?

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"];
like image 494
Kevin Driedger Avatar asked Nov 05 '09 17:11

Kevin Driedger


People also ask

How do I get AppSettings in C#?

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.

How do I get AppSettings value in console application?

You can access the config values through ConfigurationSettings. AppSettings["Your Key"].

Where is AppSettings in web config?

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.

What is the AppSettings section in the web config file?

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.


1 Answers

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

like image 133
marc_s Avatar answered Sep 21 '22 12:09

marc_s