DLL配置文件未被识别,如何读取非宿主程序的.config文件?
正确加载DLL独立配置文件的方法
问题原因
.NET配置系统默认以宿主程序的配置文件作为应用域的全局配置,直接调用ConfigurationManager.OpenExeConfiguration(DLL路径)无法正确加载DLL同名的.config文件——即使路径正确,系统仍会优先关联宿主EXE的配置上下文。
正确解决方案
需要通过ExeConfigurationFileMap显式指定配置文件路径,再用OpenMappedExeConfiguration加载独立配置,步骤如下:
- 构造DLL配置文件的完整路径:在DLL路径后追加
.config后缀 - 创建配置文件映射对象,指定目标配置文件
- 加载映射后的配置并读取目标节
修正后的代码
public static List<string> GetCategorieNames() { // 获取DLL的完整路径 string dllPath = Assembly.GetExecutingAssembly().Location; // 构造对应的.config文件路径 string configPath = $"{dllPath}.config"; // 创建配置文件映射 var configMap = new ExeConfigurationFileMap { ExeConfigFilename = configPath }; // 加载指定的配置文件 Configuration appConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); // 读取categories节(对应配置里的NameValueSectionHandler,类型为NameValueCollection) var categoriesSection = appConfig.GetSection("categories") as NameValueCollection; if (categoriesSection == null) { return new List<string>(); // 节不存在时返回空列表 } // 获取names对应的value并拆分 string namesValue = categoriesSection["names"]; if (string.IsNullOrEmpty(namesValue)) { return new List<string>(); } List<string> categoryList = Array.ConvertAll(namesValue.Split(','), s => s.Trim()).ToList(); return categoryList; }
关键细节说明
- 配置节类型匹配:你的配置里
categories节的type是System.Configuration.NameValueSectionHandler,所以读取后必须转换为NameValueCollection,而非自定义的categories类型(原代码此处存在错误) - 空值判断:增加了节不存在、值为空的判断,避免空引用异常
- 配置路径构造:确保.config文件和DLL在同一目录,路径拼接要准确
内容的提问来源于stack exchange,提问作者Charlie P
相关产品推荐
相关产品推荐

