I have a config file in a wpf project to store the connectionstring. But when I try to get AppSettings and ConnectionStrings, I get null.
the WEB.config file is like this:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="Trackboard" connectionString="Data Source=(localdb)v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:UsersSeanWorkspaceDATABASETrackboard.mdf"/> </connectionStrings> <appSettings> <add key="Trackboard" value="Data Source=(localdb)v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:UsersSeanWorkspaceDATABASETrackboard.mdf"/> </appSettings> </configuration>
I tried in several ways:
W1: ConnStr = ConfigurationManager.ConnectionStrings["Trackboard"].ConnectionString; W2: ConnStr = ConfigurationManager.ConnectionStrings[0].ConnectionString; W3: ConnStr = ConfigurationManager.AppSettings["Trackboard"]; W4: ConnStr = ConfigurationManager.AppSettings[0];
None of them worked.
But this one worked:
ConnStr = @"Data Source=(localdb)v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:UsersSeanWorkspaceDATABASETrackboard.mdf";
(That means I cannot use a config file, which is against my will) I need help.
Advertisement
Answer
I’ve figured it out! I shouldn’t have created a new config file. There is a default app.config file in the project. Now everything is fine.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> </configSections> <connectionStrings> <add name="Trackboard.Properties.Settings.TrackboardConnectionString" connectionString="Data Source=(LocalDB)v11.0;AttachDbFilename=|DataDirectory|DATABASETrackboard.mdf;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>
private static string ConnStr = ConfigurationManager.ConnectionStrings["Trackboard.Properties.Settings.TrackboardConnectionString"].ConnectionString;