65.9K
CodeProject is changing. Read more.
Home

DLL with configuration file

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.79/5 (30 votes)

May 20, 2011

CPOL
viewsIcon

201347

Using configuration files in DLL is not trivial, but is very simple.

Using configuration files in DLL is not trivial. To accomplish this, we must follow these steps:
  • Add a reference to System.Configuration
  • Add a new Application Configuration File and the name it [Your project].dll.config
  • Change the BuildAction property of the config file to Content
  • Change the Copy to Output property to "Copy Always"
After these steps, you can access the configuration file this way:
//Open the configuration file using the dll location
Configuration myDllConfig = 
       ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);
// Get the appSettings section
AppSettingsSection myDllConfigAppSettings = 
       (AppSettingsSection)myDllConfig.GetSection("appSettings");
// return the desired field 
return myDllConfigAppSettings.Settings["MyAppSettingsKey"].Value; 
Your configuration file should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="MyAppSettingsKey" value="MyValue"/>
  </appSettings>
</configuration>
That's all. Hope you enjoy this tip.