我有一个最终将成为游戏的简单 WinForms 应用程序。现在,我只是在处理它的数据访问层,但遇到了麻烦。我创建了一个名为 DataAccess
的单独项目在里面,我创建了一个本地 .mdf
SQL Server 数据库文件。我还创建了一个 app.config
文件来存储连接字符串。
这是配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="TBG_Master"
connectionString="Data Source=(localdb)\MSSQLLocalDb;Integrated Security=true;AttachDbFileName=|DataDirectory|\TBG_Master.mdf"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
为了从 app.config 文件中检索连接字符串,我使用了从 this 中提取的代码问题。
Assembly service = Assembly.GetExecutingAssembly();
ConnectionStringsSection css = ConfigurationManager.OpenExeConfiguration(service.Location).ConnectionStrings;
string cs = css.ConnectionStrings["TBG_Master"].ConnectionString;
return cs;
当它到达使用字符串作为键来拉取连接字符串的那一行时,它给了我一个空引用异常。在检查了css.ConnectionString
之后集合,其中唯一的连接字符串如下所示:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
这显然不是我的 app.config
中的内容文件,我知道没有其他 app.config
文件在我的DataAccess
项目。同样在调试之后,我知道它正在寻找正确的程序集。
为什么它给我这个连接字符串而不是正确的?
最佳答案
正如@Amy 所指出的,这不起作用的原因是连接字符串没有存储在执行程序集的 app.config 文件中。移动它之后,它现在可以正常工作了。感谢您的快速帮助:)
关于C# ConfigurationManager 从 app.config 检索错误的连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42373392/