Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ConnectionString from app.config

Tags:

c#

I'm pretty sure there's some quick and easy error in this code but somehow I've spent the last 2 hours with this and couldn't solve it.

App.config:

<configuration>
  <connectionStrings>
    <add name="BO"
        connectionString="Data Source=MyServer;Initial Catalog=BO;User ID=WebUser;Password=MyPasswd"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Class.cs:

string connectionString = getNewConnection();
using (SqlConnection conn = new SqlConnection(connectionString)) { code }

Method.

public static string getNewConnection()
{
   return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
 }

Error:

Object reference not set to an instance of an object

on the line :

return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;

EDIT:

Error image, the Spanish sentence means: Object reference not set to an instance of an object

like image 875
Daniel Sh. Avatar asked Jun 21 '12 13:06

Daniel Sh.


People also ask

How do you read ConnectionString from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

How can I get connection string from app config in VB net?

You can simply access it using My. Settings. ConnectionString.

What is ConnectionString in web config?

<connectionStrings> <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System. Data. SqlClient" />


2 Answers

It should be:

ConfigurationManager.ConnectionStrings["BO"].ConnectionString;

Edit:

You will need the corresponding libraries as well if you don't have them yet, as mentioned in the below answers I think its System.Configuration

So in full you should have:

public static string getNewConnection()
{
    return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
}
like image 72
Andrew Hagner Avatar answered Oct 29 '22 03:10

Andrew Hagner


Use these codes in the Class :

class Connection
    {
        public static string con
        {
            get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            }
        }
    }
like image 30
Ali Vojdanian Avatar answered Oct 29 '22 03:10

Ali Vojdanian