【发布时间】:2023-03-13 17:09:01
【问题描述】:
我正在尝试将连接字符串从 app.config 文件调用到 C# 代码。这是 app.config 代码:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="connectstring" value="Data Source=server111;Initial Catalog=database1; Integrated Security=False;Persist Security Info=False; User ID=username;Password=password;Encrypt=True; TrustServerCertificate=True; MultipleActiveResultSets=True"/>
</appSettings>
</configuration>
这是 C# 代码:
private SqlConnection connStudent;
connStudent = new SqlConnection(ConfigurationManager.AppSettings["connectstring"].ToString());
connStudent.Open();
代码应该是正确的,但是我得到一个空引用异常,并且在调试程序时,connStudent 始终为空并且没有得到连接字符串。 错误是“对象引用未设置为对象的实例”。
【问题讨论】:
-
我认为这不能解决您的问题,但我相信 app.config 中的“值”已经作为字符串返回,因此不需要 ToString()。
-
您显示的 C# 代码不可编译甚至无效,因此至少提供异常的完整堆栈跟踪,以便更好地确定它“可能”出现的位置。到目前为止,很可能在您的 appSettings 中找不到“connectstring”,因此
AppSettings["connectstring"]返回null。因此,请确保您的app.config文件实际上是“构建到”输出目录中,在您的可执行文件旁边,具有相同的名称(如“my.exe.config”)。
标签: c# xml app-config