Equivalent to 'app.config' for a library (

2019-01-02 17:27发布

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.

14条回答
公子世无双
2楼-- · 2019-01-02 17:46

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");
查看更多
倾城一夜雪
3楼-- · 2019-01-02 17:47

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.

查看更多
闭嘴吧你
4楼-- · 2019-01-02 17:51
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");
查看更多
泛滥B
5楼-- · 2019-01-02 17:54

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.

查看更多
心情的温度
6楼-- · 2019-01-02 17:55

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

查看更多
泪湿衣
7楼-- · 2019-01-02 18:00

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.

查看更多
登录 后发表回答