Search code examples
c#visual-studio-2010app-config

Fetching connection string from appconfig file in c#


I have the following connection string declared in my app.config file:

  <connectionStrings>
    <add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
  </connectionStrings>

When I try to fetch this connection string using the following C# code snippet, I get the value null. I am not able to obtain the connection string. Is there anything wrong in the syntax?

First attempt:

var settings = ConfigurationManager.ConnectionStrings["SqlConnectionString"];
string result = settings.ConnectionString;

Second attempt:

string result = ConfigurationSettings.AppSettings["SqlConnectionString"];

Solution

  • For a non-web project, and with app.config set up as in the OP here's what I usually do, since the config file changes names when the app is compiled (to yourapp.exe.config):

        public static Configuration ExeConfig()
        {
            Assembly service = Assembly.GetAssembly(typeof(YourClass));
            return ConfigurationManager.OpenExeConfiguration(service.Location);
        }
    

    Then to reference the s'th connection string:

    ExeConfig().ConnectionStrings.ConnectionStrings[s].ConnectionString