C#ConfigurationManager从app.config检索错误的连接字符串 [英] C# ConfigurationManager retrieves wrong connection string from app.config

查看:80
本文介绍了C#ConfigurationManager从app.config检索错误的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的WinForms应用程序,它将最终成为游戏.现在,我只是在它的数据访问层上工作,遇到了麻烦.我创建了一个名为DataAccess的单独项目,在其中创建了本地.mdf SQL Server数据库文件.我还创建了一个app.config文件来存储连接字符串.

I have a simple WinForms app that will eventually be a game. Right now, I'm just working on the data access layer of it and I've run into a snag. I created a separate project called DataAccess and inside of that, I created a local .mdf SQL Server database file. I also created an app.config file to store the connections string.

这是配置文件:

<?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文件中检索连接字符串,我正在使用从

To retrieve the connection string from the app.config file I am using code pulled from this question.

Assembly service = Assembly.GetExecutingAssembly();
ConnectionStringsSection css = ConfigurationManager.OpenExeConfiguration(service.Location).ConnectionStrings;
string cs = css.ConnectionStrings["TBG_Master"].ConnectionString;
return cs;

当到达使用字符串作为键将连接字符串拉出的行时,它给了我一个空引用异常.检查css.ConnectionString集合后,它中唯一的连接字符串如下所示:

When it gets to the line where it pulls the connection string using the string as the key, it gives me a null reference exception. After examining the css.ConnectionString collection, the only connection string it has in it looks like this:

data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

这显然不是我的app.config文件中的文件,并且我知道我的DataAccess项目中没有其他app.config文件.同样在调试之后,我知道它正在寻找正确的程序集.

This is clearly not what it is in my app.config file, and I know there is no other app.config file in my DataAccess project. Also after debugging, I know for a fact that it is looking in the right assembly.

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

Why is it giving me this connection string and not the correct one?

推荐答案

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

As @Amy pointed out, the reason this was not working was because the connection string was not stored in the executing assemblies app.config file. After moving it, it now works as it should. Thank you for the quick help :)

这篇关于C#ConfigurationManager从app.config检索错误的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆