Ammar Asjad
Ammar Asjad

Reputation: 3000

Get Connection String from Web.config in asp.net

I want to know the ways to get connection string from web.config file in asp.net.

I just only know the below way .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

    namespace Sherserve.DataAccessLayer
    {
        public class DBGateway
        {
            public static string conString;

            public DBGateway()
            {
                conString = ConfigurationManager.ConnectionStrings["test"].ToString();
            }
        }
    }

Upvotes: 31

Views: 105828

Answers (5)

K.M.
K.M.

Reputation: 31

Try

 string ConString = System.Configuration.ConfigurationManager.ConnectionStrings[ConfigurationManager.ConnectionStrings.Count -1].ConnectionString;

Upvotes: 2

CREM
CREM

Reputation: 1991

Following code works for me. I've added the exception in case connectionString not founded in web.config

web.config:

 <configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=myaddress;Initial Catalog=MyCatalog;User ID=myuser;Password=pass;Encrypt=True;TrustServerCertificate=False"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

In my connection class:

static internal string GetSqlConnectionString(){

try {
    ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings("DataBaseConnection");
    if (mySetting == null)
        throw new Exception("Database connection settings have not been set in Web.config file");

    return mySetting.ConnectionString;

} catch (Exception ex) {
    throw;
}}

Upvotes: 0

mRizvandi
mRizvandi

Reputation: 1083

I have a method on my WebAssistant Class. i have a key on appSettings that contain my WebAppName, check the below line:

<add key="DOMAIN_NAME" value="mRizvandi.com"/>

and my connection name alwyas has "DomainName"+"DBConnectionString" template such as:

<add name="mRizvandiDBConnectionString" connectionString=...

Ok, everything are ready to get connectionstring without pass any string.

    public static string GetDBConnectionString()
    {
        string retValue = "";
        string domainUrl = "";
        string connectionKey = "";
        string dbConnectionString = "";

        domainUrl = GetDomainUrl();
        connectionKey = domainUrl.Substring(0, domainUrl.IndexOf(".")) + "DBConnectionString";
        dbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionKey].ToString();
        retValue = dbConnectionString;

        return retValue;
    }

I hope would be helpful.

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66399

Using the ConfigurationManager.ConnectionStrings is about the only proper way, to use it properly with sanity check you can have such code:

public DBGateway()
{
    ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["test"];
    if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
        throw new Exception("Fatal error: missing connecting string in web.config file");
    conString = mySetting.ConnectionString;
}

This will throw useful error in case the connection string is missing, instead of cryptic "null object" error.

Worth to mention that the ConnectionStringSettings class is overriding the ToString() method:

public override string ToString()
{
    return this.ConnectionString;
}

So it means that using ConfigurationManager.ConnectionStrings["test"].ToString() is the same like ConfigurationManager.ConnectionStrings["test"].ConnectionString however you still better perform sanity check and personally it looks cleaner to use the actual property and not depend on the class to give it.

Upvotes: 49

RL89
RL89

Reputation: 1916

Here is the whole solution:-

string constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
DataSet ds = new DataSet();
try
 {
   SqlDataAdapter dataAdapter = new SqlDataAdapter(query, con);
   SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
   con.Open();
   dataAdapter.Fill(ds, "table");
   return ds;
 }
 catch (Exception ex)
  {
  }
    finally
    {
        if (con.State == System.Data.ConnectionState.Open)
            con.Close();
    }

This is how you can fetch records from database into datatable.

Hope this is what you were looking for.

Upvotes: 9

Related Questions