C# ConfigurationManager 从 app.config 中检索到错误的连接字符串

C# ConfigurationManager retrieves wrong connection string from app.config

我有一个最终将成为游戏的简单 WinForms 应用程序。现在,我只是在处理它的数据访问层,我 运行 遇到了麻烦。我创建了一个名为 DataAccess 的单独项目,并在其中创建了一个本地 .mdf SQL 服务器数据库文件。我还创建了一个 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 文件中的内容,而且我知道我的 DataAccess 项目中没有其他 app.config 文件。同样在调试之后,我知道它正在寻找正确的程序集。

为什么给我这个连接字符串而不是正确的?

正如@Amy 所指出的,这不起作用的原因是连接字符串未存储在执行程序集 app.config 文件中。移动它之后,它现在可以正常工作了。感谢您的快速帮助:)

您还可以使用 machine.config 文件来保存独立于给定计算机的任何应用程序的连接字符串。这样它们就不必位于任何 app.config 文件中,因为所有应用程序都会自动读取它们正在执行的机器上的 machine.config 文件。