[c#] Get connection string from App.config

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.

The answer is


string str = Properties.Settings.Default.myConnectionString; 

Have you tried:

var connection = new ConnectionFactory().GetConnection(
    ConfigurationManager.ConnectionStrings["Test"]
    .ConnectionString, DataBaseProvider);

Can't you just do the following:

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

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


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.


//Get Connection from web.config file
public static OdbcConnection getConnection()
{
    OdbcConnection con = new OdbcConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    return con;     
}

You can use this method to get connection string

using System; 
using System.Configuration;

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

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.


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.


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.


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


string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;

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


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


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();

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 .


Try this out

string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;

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.


This worked for me:

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

Outputs:

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


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to ado.net

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient' How to fill a datatable with List<T> Populate data table from data reader Increasing the Command Timeout for SQL command how to resolve DTS_E_OLEDBERROR. in ssis Convert DataSet to List How to connect access database in c# MySQL Data Source not appearing in Visual Studio How do I get values from a SQL database into textboxes using C#? Connection to SQL Server Works Sometimes

Examples related to exception-handling

Catching FULL exception message Spring Resttemplate exception handling How to get exception message in Python properly Spring Boot REST service exception handling java.net.BindException: Address already in use: JVM_Bind <null>:80 Python FileNotFound The process cannot access the file because it is being used by another process (File is created but contains nothing) Java 8: Lambda-Streams, Filter by Method with Exception Laravel view not found exception How to efficiently use try...catch blocks in PHP

Examples related to connection-string

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App How to read connection string in .NET Core? Connect to SQL Server Database from PowerShell System.Data.SqlClient.SqlException: Login failed for user Entity Framework change connection at runtime A network-related or instance-specific error occurred while establishing a connection to SQL Server How can I set an SQL Server connection string? VB.NET Connection string (Web.Config, App.Config) Connection string using Windows Authentication How to find SQL Server running port?

Examples related to app-config

Is ConfigurationManager.AppSettings available in .NET Core 2.0? How to read AppSettings values from a .json file in ASP.NET Core What is App.config in C#.NET? How to use it? How to make spring inject value into a static field App.Config change value Get connection string from App.config How should I edit an Entity Framework connection string? Equivalent to 'app.config' for a library (DLL) How to implement a ConfigurationSection with a ConfigurationElementCollection App.Config Transformation for projects which are not Web Projects in Visual Studio?