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?