调用ConfigurationManager.GetSection读取App.config返回null如何解决?
问题原因与解决方法
核心错误:类型转换不匹配
你在App.config中注册的自定义section类型为System.Configuration.AppSettingsSection,但代码里直接将ConfigurationManager.GetSection的返回值转换为NameValueCollection,两种类型不兼容,所以转换失败返回null,最终触发空引用异常。
正确读取代码示例
[OneTimeSetUp] public void Init() { // 先按注册的AppSettingsSection类型读取配置段 AppSettingsSection capSection = ConfigurationManager.GetSection("capabilities/" + profile) as AppSettingsSection; AppSettingsSection envSection = ConfigurationManager.GetSection("environments/" + environment) as AppSettingsSection; // 非空校验避免空引用 if (capSection == null || envSection == null) { throw new Exception("配置段读取失败,请检查配置路径是否正确"); } // 手动将AppSettingsSection的内容转为NameValueCollection NameValueCollection caps = new NameValueCollection(); foreach (KeyValueConfigurationElement kv in capSection.Settings) { caps.Add(kv.Key, kv.Value); } NameValueCollection settings = new NameValueCollection(); foreach (KeyValueConfigurationElement kv in envSection.Settings) { settings.Add(kv.Key, kv.Value); } DesiredCapabilities capability = new DesiredCapabilities(); foreach (string key in caps.AllKeys) { // 原有逻辑 } ... }
其他可能的排查点
- 确认变量值:运行时检查
profile的值是否为parallel,environment的值是否为chrome/firefox/edge三者之一,配置路径拼写错误会直接返回null - 检查App.config属性:在解决方案资源管理器右键点击App.config → 选择「属性」,确认复制到输出目录设置为「如果较新则复制」,否则编译后输出目录不会生成正确的配置文件
- 确认配置文件位置:如果当前是单元测试项目,App.config必须放在测试项目的根目录下,ConfigurationManager默认读取入口程序集的配置文件,放在其他类库项目中会无法读取
内容的提问来源于stack exchange,提问作者Kody Berry
相关产品推荐
相关产品推荐

