的app.config的图书馆当量(DLL)当量、图书馆、app、config

2023-09-02 20:41:48 作者:丿glorious灬永恒

有app.config中的DLL的等效?如果没有,什么是存储设置/配置特定于库(一个DLL)最简单的方法?该库可能在​​不同的应用中使用。

Is there an equivalent of app.config for dll's? If not, what is the easiest way to store settings/configuration that are specific to a library (a dll)? THe library might be used in different applications.

推荐答案

您可以有单独的配置文件,但你必须要读手动,该 ConfigurationManager.AppSettings [钥匙] 将读取运行的程序集只配置。

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.

首先,在VS项目右键 - >添加 - >新项目 - >应用程序配置文件

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

这将的App.config 添加到项目文件夹,把你的设置中有以下<的appSettings> 部分。

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;
}

和使用它:

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");
    ...
}

您将需要添加,当然参考System.Configuration。

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

在建项目,除DLL你必须 DllName.dll.config 文件为好,这是你要发布的DLL本身的文件

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.