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>
                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.
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.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With