ConfigurationManager throwing null exception when trying to read connection string in .NET 4.0

721 Views Asked by At

I am working on .NET Framework 4.0 Class Library project along with ADO.NET. I have connectionString inside the App.config which I am trying to read using ConfigurationManager but getting null reference exception.

Error

enter code here

app.config

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

Reading ConnectionString

using System.Configuration;

var x22 = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;

enter image description here

2

There are 2 best solutions below

2
Hadi Mazareei On

In your solution explorer and under reference node, check if assembly System.Configuration has been added related to you needed Configuration Class and there is not any error regarding to your references.

But, your code is correct and I suggest to you try to avoid this error by checking null situation in return value of that command. Maybe config file is not exist in your default path. check config file to be exist then try to read it's data.

1
Ahmed_Amr On

in app config

<connectionStrings>
    <add name="[name]" connectionString="[YOUR CONNECTION]" />
</connectionStrings>

call your connectionString

 ConfigurationManager.ConnectionStrings["name"].ConnectionString