[c#] 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.

This question is related to c# .net dll settings app-config

The answer is


Configuration files are application-scoped and not assembly-scoped. So you'll need to put your library's configuration sections in every application's configuration file that is using your library.

That said, it is not a good practice to get configuration from the application's configuration file, specially the appSettings section, in a class library. If your library needs parameters, they should probably be passed as method arguments in constructors, factory methods, etc. by whoever is calling your library. This prevents calling applications from accidentally reusing configuration entries that were expected by the class library.

That said, XML configuration files are extremely handy, so the best compromise that I've found is using custom configuration sections. You get to put your library's configuration in an XML file that is automatically read and parsed by the framework and you avoid potential accidents.

You can learn more about custom configuration sections on MSDN and also Phil Haack has a nice article on them.


use from configurations must be very very easy like this :

var config = new MiniConfig("setting.conf");

config.AddOrUpdate("port", "1580");

if (config.TryGet("port", out int port)) // if config exist
{
    Console.Write(port);
}

for more details see MiniConfig


Preamble: I'm using NET 2.0;

The solution posted by Yiannis Leoussis is acceptable but I had some problem with it.

First, the static AppSettingsSection AppSettings = (AppSettingsSection)myDllConfig.GetSection("appSettings"); returns null. I had to change it to static AppSettingSection = myDllConfig.AppSettings;

Then the return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi); doesn't have a catch for Exceptions. So I've changed it

try
{
    return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
}
catch (Exception ex)
{
    return default(T);
}

This works very well but if you have a different dll you have to rewrite every time the code for every assembly. So, this is my version for an Class to instantiate every time you need.

public class Settings
{
    private AppSettingsSection _appSettings;
    private NumberFormatInfo _nfi;

    public Settings(Assembly currentAssembly)
    {
        UriBuilder uri = new UriBuilder(currentAssembly.CodeBase);
        string configPath = Uri.UnescapeDataString(uri.Path);
        Configuration myDllConfig = ConfigurationManager.OpenExeConfiguration(configPath);
        _appSettings = myDllConfig.AppSettings;
        _nfi = new NumberFormatInfo() 
        { 
            NumberGroupSeparator = "", 
            CurrencyDecimalSeparator = "." 
        };
    }


    public T Setting<T>(string name)
    {
        try
        {
            return (T)Convert.ChangeType(_appSettings.Settings[name].Value, typeof(T), _nfi);
        }
        catch (Exception ex)
        {
            return default(T);
        }
    }
}

For a config:

<add key="Enabled" value="true" />
<add key="ExportPath" value="c:\" />
<add key="Seconds" value="25" />
<add key="Ratio" value="0.14" />

Use it as:

Settings _setting = new Settings(Assembly.GetExecutingAssembly());

somebooleanvar = _settings.Setting<bool>("Enabled");
somestringlvar = _settings.Setting<string>("ExportPath");
someintvar =     _settings.Setting<int>("Seconds");
somedoublevar =  _settings.Setting<double>("Ratio");

assemblies don't have their own app.config file. They use the app.config file of the application that is using them. So if your assembly is expecting certain things in the config file, then just make sure your application's config file has those entries in there.

If your assembly is being used by multiple applications then each of those applications will need to have those entries in their app.config file.

What I would recommended you do is define properties on the classes in your assembly for those values for example

private string ExternalServicesUrl
{
  get
  {
    string externalServiceUrl = ConfigurationManager.AppSettings["ExternalServicesUrl"];
    if (String.IsNullOrEmpty(externalServiceUrl))
      throw new MissingConfigFileAppSettings("The Config file is missing the appSettings entry for: ExternalServicesUrl");
    return externalServiceUrl;
  }
}

Here, the property ExternalServicesUrl get's its value from the application's config file. If any application using this assembly is missing that setting in the config file you'll get an exception o it's clear that something went missing.

MissingConfigFileAppSettings is a custom Exception. You may want to throw a different exception.

Of course a better design would be for the method of those classes to be provided those values as parameters rather than relying on config file setting. That way the applications using these classes can decide from where and how they provide these values.


Unfortunately, you can only have one app.config file per executable, so if you have DLL’s linked into your application, they cannot have their own app.config files.

Solution is: You don't need to put the App.config file in the Class Library's project.
You put the App.config file in the application that is referencing your class library's dll.

For example, let's say we have a class library named MyClasses.dll which uses the app.config file like so:

string connect = 
ConfigurationSettings.AppSettings["MyClasses.ConnectionString"];

Now, let's say we have an Windows Application named MyApp.exe which references MyClasses.dll. It would contain an App.config with an entry such as:

<appSettings>
    <add key="MyClasses.ConnectionString"
         value="Connection string body goes here" />
</appSettings>

OR

An xml file is best equivalent for app.config. Use xml serialize/deserialize as needed. You can call it what every you want. If your config is "static" and does not need to change, your could also add it to the project as an embedded resource.

Hope it gives some Idea


I faced the same problem and resolved it by creating a static class Parameters after adding an Application Configuration File to the project:

public static class Parameters
{
    // For a Web Application
    public static string PathConfig { get; private set; } =
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "web.config");

    // For a Class Library
    public static string PathConfig { get; private set; } =
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "LibraryName.dll.config");

    public static string GetParameter(string paramName)
    {
        string paramValue = string.Empty;

        using (Stream stream = File.OpenRead(PathConfig))
        {
            XDocument xdoc = XDocument.Load(stream);

            XElement element = xdoc.Element("configuration").Element("appSettings").Elements().First(a => a.Attribute("key").Value == paramName);
            paramValue = element.Attribute("value").Value;
        }

        return paramValue;
    }
}

Then get a parameter like this:

Parameters.GetParameter("keyName");

In response to the original question, I typically add the config file in my test project as a link; you can then use the DeploymentItem attribute to addit to the Out folder of the test run.

[TestClass]
[DeploymentItem("MyProject.Cache.dll.config")]
public class CacheTest
{
    .
    .
    .
    .
}

In response to the comments that Assemblies can't be project specific, they can and it provides great flexibility esp. when working with IOC frameworks.


Use add existing item, select the app config from dll project. Before clicking add, use the little down arrow on the right hand side of the add button to "add as link"

I do this all the time in my dev.


If you add Settings to a Class Library project in Visual Studio (Project Properties, Settings), it will add an app.config file to your project with the relevant userSettings/applicatioNSettings sections, and the default values for these settings from your Settings.settings file.

However this configuration file will not be used at runtime - instead the class library uses the configuration file of its hosting application.

I believe the main reason for generating this file is so that you can copy/paste the settings into the host application's configuration file.


Why not to use:

  • [ProjectNamespace].Properties.Settings.Default.[KeyProperty] for C#
  • My.Settings.[KeyProperty] for VB.NET

You just have to update visually those properties at design-time through:

[Solution Project]->Properties->Settings


public class ConfigMan
{
    #region Members

    string _assemblyLocation;
    Configuration _configuration;

    #endregion Members

    #region Constructors

    /// <summary>
    /// Loads config file settings for libraries that use assembly.dll.config files
    /// </summary>
    /// <param name="assemblyLocation">The full path or UNC location of the loaded file that contains the manifest.</param>
    public ConfigMan(string assemblyLocation)
    {
        _assemblyLocation = assemblyLocation;
    }

    #endregion Constructors

    #region Properties

    Configuration Configuration
    {
        get
        {
            if (_configuration == null)
            {
                try
                {
                    _configuration = ConfigurationManager.OpenExeConfiguration(_assemblyLocation);
                }
                catch (Exception exception)
                {
                }
            }
            return _configuration;
        }
    }

    #endregion Properties

    #region Methods

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

    #endregion Methods
}

Just for something to do, I refactored the top answer into a class. The usage is something like:

ConfigMan configMan = new ConfigMan(this.GetType().Assembly.Location);
var setting = configMan.GetAppSetting("AppSettingsKey");

I took a look at the AppDomain instead of the assembly. This has the benefit of working inside static methods of a library. Link seems to work great for getting the key value as suggested by the other answers here.

public class DLLConfig
{
    public static string GetSettingByKey(AppDomain currentDomain, string configName, string key)
    {
        string value = string.Empty;
        try
        {  
            string exeConfigPath = (currentDomain.RelativeSearchPath ?? currentDomain.BaseDirectory) + "\\" + configName;
            if (File.Exists(exeConfigPath))
            {
                using (Stream stream = File.OpenRead(exeConfigPath))
                {
                    XDocument xdoc = XDocument.Load(stream);
                    XElement element = xdoc.Element("configuration").Element("appSettings").Elements().First(a => a.Attribute("key").Value == key);
                    value = element.Attribute("value").Value;
                }
            }

        }
        catch (Exception ex)
        {
                
        }
        return value;
            
    }
}

Use it within your library class like so;

namespace ProjectName
{
     public class ClassName
     {
         public static string SomeStaticMethod()
         {
             string value = DLLConfig.GetSettingByKey(AppDomain.CurrentDomain,"ProjectName.dll.config", "keyname");
         }
     }
}

I am currently creating plugins for a retail software brand, which are actually .net class libraries. As a requirement, each plugin needs to be configured using a config file. After a bit of research and testing, I compiled the following class. It does the job flawlessly. Note that I haven't implemented local exception handling in my case because, I catch exceptions at a higher level.

Some tweaking maybe needed to get the decimal point right, in case of decimals and doubles, but it works fine for my CultureInfo...

static class Settings
{
    static UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
    static Configuration myDllConfig = ConfigurationManager.OpenExeConfiguration(uri.Path);
    static AppSettingsSection AppSettings = (AppSettingsSection)myDllConfig.GetSection("appSettings");
    static NumberFormatInfo nfi = new NumberFormatInfo() 
    { 
        NumberGroupSeparator = "", 
        CurrencyDecimalSeparator = "." 
    };

    public static T Setting<T>(string name)
    {
        return (T)Convert.ChangeType(AppSettings.Settings[name].Value, typeof(T), nfi);
    }
}

App.Config file sample

<add key="Enabled" value="true" />
<add key="ExportPath" value="c:\" />
<add key="Seconds" value="25" />
<add key="Ratio" value="0.14" />

Usage:

  somebooleanvar = Settings.Setting<bool>("Enabled");
  somestringlvar = Settings.Setting<string>("ExportPath");
  someintvar =     Settings.Setting<int>("Seconds");
  somedoublevar =  Settings.Setting<double>("Ratio");

Credits to Shadow Wizard & MattC


As far as I'm aware, you have to copy + paste the sections you want from the library .config into the applications .config file. You only get 1 app.config per executable instance.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to dll

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer PHP 7: Missing VCRUNTIME140.dll How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'? WampServer: php-win.exe The program can't start because MSVCR110.dll is missing msvcr110.dll is missing from computer error while installing PHP installing JDK8 on Windows XP - advapi32.dll error The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there Loading DLLs at runtime in C# Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

Examples related to settings

How to configure "Shorten command line" method for whole project in IntelliJ Error: Module not specified (IntelliJ IDEA) Instant run in Android Studio 2.0 (how to turn off) How do I open phone settings when a button is clicked? Google Chrome: This setting is enforced by your administrator maven command line how to point to a specific settings.xml for a single command? Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty Python: How would you save a simple settings/config file? How to set my phpmyadmin user session to not time out so quickly? Setting DEBUG = False causes 500 Error

Examples related to app-config

Is ConfigurationManager.AppSettings available in .NET Core 2.0? How to read AppSettings values from a .json file in ASP.NET Core What is App.config in C#.NET? How to use it? How to make spring inject value into a static field App.Config change value Get connection string from App.config How should I edit an Entity Framework connection string? Equivalent to 'app.config' for a library (DLL) How to implement a ConfigurationSection with a ConfigurationElementCollection App.Config Transformation for projects which are not Web Projects in Visual Studio?