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

Time:07-24

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

CodePudding user response:

In your solution explorer and under reference node, check if assembly System.Configuration has been added 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.

CodePudding user response:

in app config

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

call your connectionString

 ConfigurationManager.ConnectionStrings["name"].ConnectionString

  • Related