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

SlimsGhost
  • 2,849
  • 1
  • 10
  • 16
Moham ad Jafari
  • 4,399
  • 2
  • 15
  • 3
  • 5
    Where did you put that App.config? Project of application you're running or maybe some dll? You need first – abatishchev Jun 30 '11 at 15:02
  • 3
    Add a reference to System.Configuration.dll, and you should be able to use the System.Configuration.ConfigurationManager. – daszarrin Jul 22 '13 at 10:27
  • Your connection string has a typo. You need a space between "Integrated" and "Security" – Onur Omer Aug 23 '16 at 18:34
  • @OnurOmer - question has been updated to include the space ("Integrated Security" instead of "IntegratedSecurity") – SlimsGhost Mar 14 '17 at 15:39

22 Answers22

551

You can just do the following:

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

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

Andrew
  • 18,680
  • 13
  • 103
  • 118
Duffp
  • 5,878
  • 2
  • 15
  • 16
  • 21
    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").ConnectionString` for those of us who have to maintain VB code – jfa Feb 14 '17 at 16:43
318

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

Mehrad
  • 4,093
  • 4
  • 43
  • 61
Fredrick Gauss
  • 5,126
  • 1
  • 28
  • 44
  • 26
    Love this answer. By default in my version of VS (VS2012 Ultimate) this library is not included, but `using System.Configuration` still works – David Colwell Jul 12 '13 at 04:04
  • 4
    I really HAD TO add the reference or the using was not underlined but still ConfigurationManager unknown. Thanks! – CodingYourLife Dec 13 '17 at 15:09
36
string str = Properties.Settings.Default.myConnectionString; 
Celeo
  • 5,583
  • 8
  • 39
  • 41
gjijo
  • 1,206
  • 12
  • 15
  • 2
    What if app.config is added as a link to a project ? – FrenkyB Apr 08 '15 at 19:50
  • 4
    This will only work if your connection string is an app setting, it will not work if to retrieve `` elements from app.config (which is what the OP is asking for!). – BrainSlugs83 May 02 '18 at 19:52
33

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.

Carl Heinrich Hancke
  • 2,660
  • 1
  • 30
  • 35
31

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.

John Smith
  • 7,243
  • 6
  • 49
  • 61
Tapan kumar
  • 6,719
  • 1
  • 24
  • 25
17
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
    OdbcConnection con = new OdbcConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    return con;     
}
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Gobind Mandal
  • 221
  • 3
  • 2
7

Try this out

string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
John Smith
  • 7,243
  • 6
  • 49
  • 61
vishu9219
  • 761
  • 6
  • 14
4

This worked for me:

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

Outputs:

Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True"

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Talha Imam
  • 1,046
  • 1
  • 20
  • 22
3

1) Create a new form and add this:

Imports System.Configuration
Imports Operaciones.My.MySettings

Public NotInheritable Class frmconexion

    Private Shared _cnx As String
    Public Shared Property ConexionMySQL() As String
        Get
            Return My.MySettings.Default.conexionbd
        End Get
        Private Set(ByVal value As String)
            _cnx = value
        End Set
    End Property

End Class

then when you want to use the connection do this in ur form:

 Private Sub frmInsert_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim cn As New MySqlConnection(frmconexion.ConexionMySQL)
cn.open()

and thats it. You will be connected to the DB and can do stuff.

This is for vb.net but the logic is the same.

John Smith
  • 7,243
  • 6
  • 49
  • 61
OREO
  • 31
  • 1
3

It is possible that the OP in this question is trying to use an App.Config within a dll.

In this case, the code is actually trying to access the App.Config of the executable and not the dll. Since the name is not found, you get a Null returned, hence the exception shown.

The following post may be helpful: ConnectionString from app.config of a DLL is null

Community
  • 1
  • 1
Andrew
  • 702
  • 7
  • 24
3

I had the same Issue. my solution was built up from two projects. A Class library and a website referencing to the class library project. the problem was that i was trying to access the App.config in my Class library project but the system was searching in Web.config of the website. I put the connection string inside Web.config and ... problem solved!

The main reason was that despite ConfigurationManager was used in another assembly it was searching inside the runnig project .

AmiNadimi
  • 5,129
  • 3
  • 39
  • 55
3

Have you tried:

var connection = new ConnectionFactory().GetConnection(
    ConfigurationManager.ConnectionStrings["Test"]
    .ConnectionString, DataBaseProvider);
niico
  • 11,206
  • 23
  • 78
  • 161
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
3

The answers above didn't elaborate where the value in connectionStrings index comes from.

As mentioned above, to get your connection string, you say:

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

To use the correct value of XXX, go to your main projects web.config file and look for the following piece of code:

<connectionStrings>
    <add name="Authentication" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Authentication;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Authentication.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>

Where it says name= , the text within those proceeding quotes is the value of XXX you use in the code above. In my example above, it happens to be Authentication

Dean P
  • 1,841
  • 23
  • 23
2
string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;
j0k
  • 22,600
  • 28
  • 79
  • 90
khatami
  • 21
  • 1
2

It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.

Chandra Malla
  • 2,399
  • 22
  • 12
2

First you have to add System.Configuration reference to your project and then use below code to get connection string.

_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
2

You can use this method to get connection string

using System; 
using System.Configuration;

private string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;
}
1

You can fetch the connection string by using below line of code -

using System; using System.Configuration;

var connectionString=ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

Here is a reference : Connection String from App.config

somesh
  • 3,508
  • 4
  • 16
  • 10
1

I referenced System.Configuration library and I have the same error. The debug files had not their app.config, create manually this file. The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.

John Smith
  • 7,243
  • 6
  • 49
  • 61
jjcaicedo
  • 11
  • 1
1

I solved the problem by using the index to read the string and checking one by one. Reading using the name still gives the same error.
I have the problem when I develop a C# window application, I did not have the problem in my asp.net application. There must be something in the setting which is not right.

dew17
  • 11
  • 2
1

In order to read the connection string from app.cfg (in windows service application) the below code worked for me

 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
    connectionStringsSection.ConnectionStrings["CONNECTIONSTR"].ConnectionString = @"New Connection String";
Dharman
  • 30,962
  • 25
  • 85
  • 135
SaddamBinSyed
  • 553
  • 3
  • 17
1

Encountered this issue while placing ConfigurationManager.ConnectionStrings in UserControl's constructor, and none of the solution here worked for me.

After some research, seems like ConfigurationManager.ConnectionStrings would be null while trying to access it from the DesignTime.

And from this post, I came up with this following code to detect DesignTime as a workaround to the issue:

public class MyUserControl : UserControl 
{
    ....
    public MyUserControl ()
    {
        InitializeComponent();

        bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
        if (!designMode)
        {
            this.connectionString = 
                ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
        }
    }
}

Rohim Chou
  • 907
  • 10
  • 16