通常,您会被告知无法执行此操作。但是,您当然可以使用 System.Configuration.ConfigurationManager.OpenExeConfiguration 方法加载配置文件。您可以将文件路径传递给您的程序集(它不必是可执行文件,尽管有方法名称)。
当然,这不会将程序集的配置设置合并到正在执行的应用程序的配置设置中,我认为不应该这样做。您的程序集只需知道它需要通过与 System.Configuration.ConfigurationManager.GetSection 函数或该类的静态 AppSettings 属性不同的机制来检索其设置。
以下是“设置”类的一个非常简单的示例,该类为它所属的程序集加载 .config 文件。
public static class Settings
{
public static System.Configuration.Configuration Configuration { get; private set; }
static Settings()
{
// load a .config file for this assembly
var assembly = typeof(Settings).Assembly;
Configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(assembly.Location);
if (Configuration == null)
throw new System.Configuration.ConfigurationErrorsException(string.Format("Unable to load application configuration file for the assembly {0} at location {1}.", assembly.FullName, assembly.Location));
}
// This function is only provided to simplify access to appSettings in the config file, similar to the static System.Configuration.ConfigurationManager.AppSettings property
public static string GetAppSettingValue(string key)
{
// attempt to retrieve an appSetting value from this assembly's config file
var setting = Configuration.AppSettings.Settings[key];
if (setting != null)
return setting.Value;
else
return null;
}
}
还有用法……
public class UsageExample
{
void Usage()
{
string mySetting = Settings.GetAppSettingValue("MySetting");
var section = Settings.Configuration.GetSection("MySection");
}
}
现在,您仍然需要解决构建问题。将“应用程序配置文件”(App.config) 项添加到类库程序集确实会导致 Visual Studio 将其作为 .dll.config 复制到该程序集的输出文件夹,但不会自动复制到任何可执行应用程序的输出文件夹那个引用那个项目。因此,您需要添加一个构建后步骤以将文件复制到适当的位置,如您所述。
我会考虑在类库上进行构建后步骤,将 .config 文件复制到解决方案级别的“配置”文件夹,然后对可执行项目进行构建后步骤,以从“配置”文件夹到输出文件夹。我不确定这是否真的有效,但如果有效,那么您就不会在构建后步骤中在项目之间创建额外的依赖关系(这可能会使维护变得困难)。
编辑:最终,您应该考虑这是否真的是您想要做的。这不是正常的方法,通常使用 configSource 属性提到的这个问题的其他答案可能会更好地为您服务。
这种方法的缺点可能并不明显,即您无法将第三方组件的设置放入类库的配置文件并期望它们被使用。例如,如果您的类库使用 log4net,则不能将 log4net 的设置放在类库的配置文件中,因为 log4net 组件仍然希望从可执行文件的配置文件中加载设置。