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();
}
}
}
Using the
ConfigurationManager.ConnectionStringsis about the only proper way, to use it properly with sanity check you can have such code:This will throw useful error in case the connection string is missing, instead of cryptic “null object” error.
Worth to mention that the
ConnectionStringSettingsclass is overriding theToString()method:So it means that using
ConfigurationManager.ConnectionStrings["test"].ToString()is the same likeConfigurationManager.ConnectionStrings["test"].ConnectionStringhowever 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.