Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read connection string from web.config

People also ask

How do you read a connection string?

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

Where do I put ConnectionString in web config?

config file in the Views folder.) Find the <connectionStrings> element: Add the following connection string to the <connectionStrings> element in the Web. config file.

What is connection string providerName?

The providerName attribute tells users of the connection string which .NET Framework Data Provider to use when communicating with the database. The content of the connectionString attribute tells them which server to communicate with and the name of the database.


You need to add a reference to System.Configuration and then use:

System.Configuration.ConfigurationManager.
    ConnectionStrings["connectionStringName"].ConnectionString;

Add System.Configuration as a reference.

For some bizarre reason it's not included by default.


C#

// Add a using directive at the top of your code file    
using System.Configuration;

// Within the code body set your variable    
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;

VB

' Add an Imports statement at the top of your code file    
Imports System.Configuration

' Within the code body set your variable    
Dim cs as String = ConfigurationManager.ConnectionStrings("connectionStringName").ConnectionString

Add System.Configuration as a reference then:

 using System.Configuration;

 ...

 string conn = 
    ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;

I guess you need to add a reference to the System.Configuration assembly if that have not already been added.

Also, you may need to insert the following line at the top of your code file:

using System.Configuration;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;  

C#

string constring = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constring))

BELOW WEB.CONFIG FILE CODE

<connectionStrings>
    <add name="ABCD" connectionString="Data Source=DESKTOP-SU3NKUU\MSSQLSERVER2016;Initial Catalog=TESTKISWRMIP;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

In the above Code ABCD is the Connection Name


In VB : This should work

ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString

In C# it would be (as per comment of Ala)

ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString