Louis Rhys Louis Rhys - 4 years ago 145
C# Question

Equivalent to 'app.config' for a library (DLL)

Is there an equivalent to

app.config
for libraries (DLLs)? If not, what is the easiest way to store configuration settings that are specific to a library? Please consider that the library might be used in different applications.

Answer Source

You can have separate configuration file, but you'll have to read it "manually", the ConfigurationManager.AppSettings["key"] will read only the config of the running assembly.

First, in the VS project right click --> Add --> New item --> Application Configuration File

This will add App.config to the project folder, put your settings in there under <appSettings> section.

Now to read from this file have such function:

string GetAppSetting(Configuration config, string key)
{
    KeyValueConfigurationElement element = config.AppSettings.Settings[key];
    if (element != null)
    {
        string value = element.Value;
        if (!string.IsNullOrEmpty(value))
            return value;
    }
    return string.Empty;
}

And to use it:

Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;
try
{
    config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception ex)
{
    //handle errror here.. means DLL has no sattelite configuration file.
}

if (config != null)
{
    string myValue = GetAppSetting(config, "myKey");
    ...
}

You'll have to add reference to System.Configuration of course.

When building the project, in addition to the DLL you'll have DllName.dll.config file as well, that's the file you have to publish with the DLL itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download