Reputation: 81
I have two projects. One is web & the other is windows forms. Web project connects to database but the windows project throws an exception NullReferenceException reading the connection string.
I am using the same classes to connect both projects. Connection is established using LINQTOSQL.
Here is my Connection string:
<connectionStrings>
<add name="GPSystemConnectionString"
connectionString="Data Source=.;Initial Catalog=GPSystem;User ID=***;Password=***"
providerName="System.Data.SqlClient" />
</connectionStrings>
This is how i am reading it.
string CS = ConfigurationManager.ConnectionStrings["GPSystemConnectionString"].ConnectionString;
(Exception occurs on this line)..... (Object reference not set to an instance of an object.)
Note: i am using same class to connect both projects.... one connects but the other fails.
Please any one help me with this!
Thank you in advance.
Upvotes: 8
Views: 19640
Reputation: 141
I always struggle with this issue of null reference with the ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
when I have the data access layer in a different project/library than the executable. I often use the following to help debug the location of the configuration file at runtime:
var configfile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var path = configfile.FilePath;
Upvotes: 8
Reputation: 529
In my case this issue was due to ConnectionString in my 64bit Machine.Config
C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\Config
Rather than the standard 32-bit
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config
To correct remove the Prefer 32-bit setting on the Build tab of Project Properties
Upvotes: 0
Reputation: 157136
If you want to get the configuration section from another assembly use this:
Assembly assembly = ...; /* get the assembly to read config from */
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(assembly.Location);
string CS = configuration.ConnectionStrings["GPSystemConnectionString"].ConnectionString;
Upvotes: 4
Reputation: 17604
You need to have entry in app.config for connection string in your window application.
If you don't have App.Config
file then add it.
and put entry like below
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="GPSystemConnectionString" connectionString="..." />
</connectionStrings>
</configuration>
In you .cs file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
var connectionString=ConfigurationManager.ConnectionStrings["GPSystemConnectionString"].ConnectionString;
Upvotes: 12