C# ConfigurationManager retrieves wrong connection string from app.config

a 夏天 提交于 2020-01-02 07:06:16

问题


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.

Here's that config file:

<?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>

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;

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

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?


回答1:


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 :)




回答2:


You can also use the machine.config file to hold connection strings that are independent of any application for a given machine. That way they don't have to be in any app.config file, because all applications automatically read the machine.config file on the machine they are executing on.



来源:https://stackoverflow.com/questions/42373392/c-sharp-configurationmanager-retrieves-wrong-connection-string-from-app-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!