问题
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