Fetching connection string from appconfig file in c#

42,571

Solution 1

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

Solution 2

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"];

Solution 3

I am doing this to get my connect string "OracleDbContext"...

ConfigurationManager.ConnectionStrings["OracleDbContext"].ConnectionString;

my web.config looks like:

  <connectionStrings>
    <add name="OracleDbContext" 
         providerName="Oracle.ManagedDataAccess.Client" 
         connectionString="User Id=oracle_user;              
                           Password=oracle_user_password;
                           Data Source=oracle" />
  </connectionStrings>

Solution 4

Am having the same problem but after much research, i discovered that the reason why the code is throwing a null reference exception is because if you use the connectionString name, it will return null and when you try to call a the ToString() or the ConnectionString property of the ConfigurationManager.ConnectionStrings property that's when the exception is thrown, so to
return the correct connection string, you have to index into the ConnectionStringSettings using the following code.

ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings[/* index */];

string conString = conSettings.ConnectionString;

Solution 5

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

Share:
42,571
mahesh
Author by

mahesh

Updated on July 09, 2022

Comments

  • mahesh
    mahesh almost 2 years

    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"];
    
  • Edward Zhu
    Edward Zhu over 12 years
    How do you find out this error? If you are debugging the code in VS, please confirm that the <appName>.vshost.exe.config does exist. VS debug will use this configuration file.
  • Kurt Koller
    Kurt Koller over 11 years
    Seems like you'd want this to be the name of the initial assembly if you had this in a library or something, and so then it seems that'd you'd want to use Assembly.GetEntryAssembly()
  • TChadwick
    TChadwick almost 11 years
    This is the only way I could find to get the settings in a .Net 4.5 Console App
  • Hakoo Desai
    Hakoo Desai over 10 years
    I am trying this in Visual Studio 2008 and getting error that "ConnectionString has invalid child element "appSettings"
  • honzakuzel1989
    honzakuzel1989 about 8 years
    Obsolete method.. Use ConfigurationManager.AppSettings["SqlConnectionString"] instead. Note: connection must be directly in appSettings section (not ideal for some reasons).
  • honzakuzel1989
    honzakuzel1989 about 8 years
    You can use Assembly.GetExecutingAssembly() instead Assembly.GetAssembly(typeof(YourClass)) - YourClass is confusing (whitch class?).