Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read the connection string from App.config file by C#

Tags:

c#

.net

c#-4.0

I'm using this code to read the connection string from my app.config file but it always return a null value. My App.config file is under my project. Both methods are resulting null values:

public SqlConnection getConnection()
{
    try
    {
        // connectionString = ConfigurationManager.AppSettings["dbConn"];

        connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
        connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"];
        sqlConnection = new SqlConnection(connectionString);  

        sqlConnection = new SqlConnection(connectionString);
    }
    catch (Exception ex)
    {

    }
    return sqlConnection;
}

This is my app.config file declaration:

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
  <connectionStrings>
    <add name="dbConn" providerName="System.Data.SqlClient"
          connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User  Id=sa;Password=123" />
  </connectionStrings>
</configuration>
like image 205
Gayan Kalanamith Avatar asked Mar 25 '12 10:03

Gayan Kalanamith


2 Answers

I think your problem that you try to read connection string twice, first you do it right, and second time you do it wrong, so just remove second line:

connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
sqlConnection = new SqlConnection(connectionString); 

ConfigurationManager.AppSettings used to access <appSettings>...</appSettings> section of the config.

like image 198
Alexander Avatar answered Oct 01 '22 00:10

Alexander


Can you please try

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
  <connectionStrings>
    <add name="dbConn" providerName="System.Data.SqlClient"
          connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User  Id=sa;Password=123" />
  </connectionStrings>
  <appSettings>
    <add key="dbConn"  value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User  Id=sa;Password=123" />
  </appSettings>
</configuration>

Then use the second method.

Make sure you select the App.Config file in the solution explorer and in the property window select Copy to Output Directory to Copy Always. Now Build the application and try again.

See the screenshot

like image 27
PraveenVenu Avatar answered Sep 30 '22 23:09

PraveenVenu