对于库 (DLL) 是否有等同于 app.config
的东西?如果没有,存储特定于库的配置设置的最简单方法是什么?请考虑该库可能用于不同的应用程序。
最佳答案
您可以有单独的配置文件,但您必须“手动”阅读它,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 项目中,您应该将 .config 文件“复制到输出目录”设置设置为“始终复制”。
以上为基本示例代码,对全尺寸示例感兴趣的 friend 请引用this other answer .
关于c# - 相当于库 (DLL) 的 'app.config',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5190539/