sithira pathirana
sithira pathirana

Reputation: 81

Get connection string using app.config file in C#

I want to get connection string using app.config file

this is my app.config file :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>    
    <add name="MSSConStr"
        connectionString="Data Source=Sithi-PC;Initial Catalog=mssdb2;User ID=XXXXX;Password=YYYYYYY"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

string x = ConfigurationManager.ConnectionStrings["MSSConStr"].ConnectionString;

this statement gives a exception "Object reference not set to an instance of an object."

Please can u help me to correct this error!!! this is working properly in .NET framework 3.5 project. But this project is .NET framework 4.0. I added the reference "System.Configuration" to my project and use it in my Database Access class. Thank you!!!

EDIT: Addional Code:

public static SqlConnection getNewConnection() 
{ 
    string x = ConfigurationManager.ConnectionStrings["MSSConStr"].ConnectionString.ToString(); 
    con2 = new SqlConnection(x); 
    return con2; 
}

Upvotes: 0

Views: 13246

Answers (1)

competent_tech
competent_tech

Reputation: 44971

There are two possible issues:

1) You have some settings elsewhere in the app (settings, code, etc, that is unintentionally clearing the connection strings (unlikely, but possible).

2) The .config that is being used at run time does not have the connection string propagated to it. If you are running in debug mode, open windows explorer, navigate to the bin/debug directory and open the .exe.config or .vshost.exe.config file and see if the connection string is set correctly there. If it isn't, stop the application, clear the directory, and try again. If the problem persists, see item #1.

Upvotes: 2

Related Questions