Mar 18, 2009

Read the connection string from the web.config file

Here is this code, it is replicated bilions of time in Internet, yet I fill obliged to paste it here...

This is the first way, which I took from Microsoft.
It checks if there is a connection strings section, then it checks if the count of connection strings is more than zero:

        System.Configuration.
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
        System.Configuration.
ConnectionStringSettings connString;
        
if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
        {
           connString =
             rootWebConfig.ConnectionStrings.ConnectionStrings[
"MyConnectionString"];
          
if (null != connString)
           {
            
// Do something with the string, for example - create SqlConnection object:
             SqlConnection con = new SqlConnection(rootWebConfig.ConnectionStrings.ConnectionStrings["MyConnectionString"].ConnectionString);
           }
        }


This one is the short line (no checks if anything fails, after all if you don't have a connection string in 99% of the scenarios you will want to have exception rised).

string cString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["mine"].ConnectionString;

No comments: