You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在.NET Framework 4.0中用ConfigurationManager读连接字符串抛空引用异常

.NET Framework 4.0类库读取连接字符串空引用异常解决

问题场景

开发基于.NET Framework 4.0的Class Library类库项目,使用ADO.NET操作数据库,已在项目的App.config中配置连接字符串,但通过ConfigurationManager读取时触发空引用异常。

相关代码与配置

App.config配置内容

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
 <connectionStrings>
    <add name ="dbConnection" connectionString="Data Source=xyz;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

读取连接字符串的代码

using System.Configuration;

var x22 = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;

排查与解决方法

  • 类库配置读取规则:类库本身不会加载自身的App.config,运行时会读取**调用该类库的宿主程序(如控制台应用、WinForm程序等)**的配置文件。需将连接字符串配置到宿主程序的App.config/Web.config中,而非类库的App.config。
  • 检查程序集引用:确认项目已引用System.Configuration程序集(右键项目→添加引用→找到System.Configuration并勾选)。
  • 检查名称拼写:确认代码中读取的连接字符串名称dbConnection与配置文件中的name属性完全一致,注意大小写敏感。
  • 验证配置格式:确保App.config的connectionStrings节点格式正确,无XML语法错误。

内容的提问来源于stack exchange,提问作者K.Z

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:36:18