I have the following connection string declared in my app.config
file:
First, you must add the appSettings
tag
<connectionStrings>
<appSettings>
<add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
</appSettings>
</connectionStrings>
Second, add a reference to System.Configuration
to your project and insert a using System.Configuration
in the source.
Then, you can use ConfigurationManager.AppSettings
to access your config setting:
string result = ConfigurationSettings.AppSettings["SqlConnectionString"];
One thing I've noticed when compiling WinForm App in VS 2013:
I add connection strings my Settings File - which updates my app.config file
When I would expect:
var connectionString = ConfigurationManager.ConnectionStrings["theConnectionStringName"].ConnectionString;
I have to write:
var connectionString = ConfigurationManager.ConnectionStrings["MyAppNameSpace.Properties.Settings.theConnectionStringName"].ConnectionString;
Everything else is business as usual
Same problem. Based on Merlyn Morgan-Graham and Edward Zhu comments, I rebuilt my project, which used the app.config to create a myapp.exe.config file with the connection string. Original first syntax then worked.
Other problem: Tried using the project properties dialog to modify the connection string and it added "project.My.Mysettings. to the connection string name. Which caused failure.
<configuration>
<appSettings>
<add key="ConnectionString" value="blah blah blah"/> </appSettings>
</configuration>
Will the above configuration works with the API/code like:
string str = ConfigurationSettings.AppSettings["SqlConnectionString"];