This is just a quick post because I couldn’t find this information easily available on other sites. I knew there was a quick way to access the connection strings from the web.config file (and other app settings) without going through some crazy XML reader or doing something ridiculous like what http://msdn.microsoft.com/en-us/library/ms178411.aspx. I’m sure this is on the internet somewhere, but the more places the better as far as I’m concerned. If you simply add the System.Configuration to your ‘using’ list you can use the ConfigurationManager class which exposes the AppSettings and ConnectionStrings easily. In this way you can access the ConnectionString from this single line instead of the block of ugliness MSDN suggests.
ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString
Oh, by the way, this is the MSDN madness:-)
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
if (connString != null)
Console.WriteLine("Northwind connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
Posted By: Joe Basirico