Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing database connection string using app.config in C# winform

Tags:

I can't seem to be able to access the app.config database connection string in my c# winforms app.

app.config code

   <connectionStrings>
      <add name="MyDBConnectionString" providerName="System.Data.SqlClient"
            connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
   </connectionStrings>  

C# code:

SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["MyDBConnectionString"];    

When I try the C# code, I get a message:
Warning 1 'System.Configuration.ConfigurationSettings.AppSettings' is obsolete: ' This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'

However, when I try to use:

conn.ConnectionString = System.Configuration!System.Configuration.ConfigurationManager.AppSettings["MyDBConnectionString"];  

I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

like image 882
Troy Avatar asked Dec 12 '11 14:12

Troy


People also ask

Where is connection string in app config?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file.

How do you read connectionString from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].


2 Answers

This is all you need:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
like image 102
CSharpened Avatar answered Sep 30 '22 16:09

CSharpened


Use ConfigurationManager instead of ConfigurationSettings. It has a ConnectionStrings property that you should use for connection strings in the connectionStrings section:

ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
like image 29
Oded Avatar answered Sep 30 '22 14:09

Oded