对于库(DLL),是否有相当于app.config
的值?如果不是,存储特定于库的配置设置的最简单方法是什么?请考虑该库可能在不同的应用程序中使用.
对于库(DLL),是否有相当于app.config
的值?如果不是,存储特定于库的配置设置的最简单方法是什么?请考虑该库可能在不同的应用程序中使用.
您的can有单独的配置文件,但您必须"手动"读取它,ConfigurationManager.AppSettings["key"]
将只读取正在运行的程序集的配置.
假设您使用Visual Studio作为IDE,可以右键单击所需的项目→ 添加→ 新项目→ 应用程序配置文件
这将增加App.config
到项目文件夹中,把你的设置放在<appSettings>
节下面.如果您没有使用Visual Studio并手动添加文件,请确保为其指定这样的名称:DllName.dll.config,否则下面的代码将无法正常工作.
现在要从该文件中读取,请执行以下操作:
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命名空间的引用,才能使ConfigurationManager类可用.
在构建项目时,除了DLL之外,您还将有DllName.dll.config
个文件,这是您必须使用DLL本身发布的文件.
在VS项目中,您应该设置.配置文件"复制到输出目录"设置为"始终复制".
以上是基本的示例代码,对于那些对完整示例感兴趣的人,请参考this other answer.