[c#] How to write connection string in web.config file and read from it?

I'm trying to write Connection string to Web.config like this:

<connectionStrings>
  <add name="Dbconnection" connectionString="Server=localhost; 
       Database=OnlineShopping ; Integrated Security=True"/>
</connectionStrings >

and read from it like this:

string strcon = 
    ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);

when run the program I get an error because of the null reference. but when I use this code:

SqlConnection DbConnection = new SqlConnection();
DbConnection.ConnectionString = 
    "Server=localhost; Database=OnlineShopping ; Integrated Security=True";

I don't get any error and the program works correctly! What is the problem?

This question is related to c# asp.net sqlconnection

The answer is


Try to use WebConfigurationManager instead of ConfigurationManager


After opening the web.config file in application, add sample db connection in connectionStrings section like this:

<connectionStrings>  
    <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />   
</connectionStrings>  

Declaring connectionStrings in web.config file:

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

There is no need of username and password to access the database server. Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

using System.Configuration;

This namespace is used to get configuration section details from web.config file.

using System;  
using System.Data.SqlClient;  
using System.Configuration;  
public partial class _Default: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {  
        //Get connection string from web.config file  
        string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
        //create new sqlconnection and connection to database by using connection string from web.config file  
        SqlConnection con = new SqlConnection(strcon);  
        con.Open();  
    }  
}  

Add reference to add System.Configuration:-

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

Also you can change the WebConfig file to include the provider name:-

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping;
       Integrated Security=True"; providerName="System.Data.SqlClient" />
</connectionStrings>

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Web.config:

<connectionStrings>
    <add name="ConnStringDb" connectionString="Data Source=localhost;
         Initial Catalog=DatabaseName; Integrated Security=True;" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

c# code:

using System.Configuration;
using System.Data

SqlConnection _connection = new SqlConnection(
          ConfigurationManager.ConnectionStrings["ConnStringDb"].ToString());

try
{
    if(_connection.State==ConnectionState.Closed)
        _connection.Open();
}
catch { }

Try this After open web.config file in application and add sample db connection in connectionStrings section like this

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >

try this

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to sqlconnection

How to write connection string in web.config file and read from it? How to run multiple SQL commands in a single SQL connection? SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application Changing SqlConnection timeout How to use the ConfigurationManager.AppSettings Check if SQL Connection is Open or Closed in a "using" block is a SqlConnection closed on return or exception?