Get connection string from App.config

757,844

Solution 1

You can just do the following:

var connection = 
    System.Configuration.ConfigurationManager.
    ConnectionStrings["Test"].ConnectionString;

Your assembly also needs a reference to System.Configuration.dll

Solution 2

Since this is very common question I have prepared some screen shots from Visual Studio to make it easy to follow in 4 simple steps.

get connection string from app.config

Solution 3

string str = Properties.Settings.Default.myConnectionString; 

Solution 4

Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.

Solution 5

First Add a reference of System.Configuration to your page.

using System.Configuration;

Then According to your app.config get the connection string as follow.

string conStr = ConfigurationManager.ConnectionStrings["Test"].ToString();

That's it now you have your connection string in your hand and you can use it.

Share:
757,844
Admin
Author by

Admin

Updated on February 15, 2022

Comments

  • Admin
    Admin about 2 years
    var connection = ConnectionFactory.GetConnection(
        ConfigurationManager.ConnectionStrings["Test"]
        .ConnectionString, DataBaseProvider);
    

    And this is my App.config:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <connectionStrings>
            <add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
        </connectionStrings>
    </configuration>
    

    But when my project runs this is my error:

    Object reference not set to an instance of an object.

  • David Colwell
    David Colwell almost 11 years
    Love this answer. By default in my version of VS (VS2012 Ultimate) this library is not included, but using System.Configuration still works
  • FrenkyB
    FrenkyB about 9 years
    What if app.config is added as a link to a project ?
  • Amit Sinha
    Amit Sinha over 7 years
    I did the same as u said but same null reference error I am getting.
  • Jacqlyn
    Jacqlyn about 7 years
    I know that this is a C# question, but since this is the top of the google search results, to do this in VB, it's System.Configuration.ConfigurationManager.ConnectionStrings(‌​"Test").ConnectionSt‌​ring for those of us who have to maintain VB code
  • CodingYourLife
    CodingYourLife over 6 years
    I really HAD TO add the reference or the using was not underlined but still ConfigurationManager unknown. Thanks!
  • BrainSlugs83
    BrainSlugs83 almost 6 years
    This will only work if your connection string is an app setting, it will not work if to retrieve <connectionStrings> elements from app.config (which is what the OP is asking for!).