Personal Blog of Mustafa Basgun

Posts Tagged ‘asp.net dll

Getting Connection String From Web.Config Inside A DLL Code

leave a comment »

I have been working on creating some .NET dlls at work which would commonly be utilized by our web applications. And, one of the requirements was getting the connection string information from web.config file. Simply making the call by using the ConfigurationManager class wouldn’t work since it was giving some kind of compile time error when you try to build the dll. So, I needed to find a workaround to retrieve the connection string from either connectionStrings or appSettings elements. Here is the solution that I have figured out so far.

Necessary namespaces:

mustafa-basgun-blog-aspnet-connstring-webcofig-1

Generic function that grabs the information based on your connection string name:

mustafa-basgun-blog-aspnet-connstring-webcofig-2

Sample usage:

mustafa-basgun-blog-aspnet-connstring-webcofig-3

To understand the ConnectionStringSettingsCollection and NameValueCollection classes, followings links would be helpful:

http://msdn.microsoft.com/en-us/library/system.configuration.connectionstringsettingscollection.aspx
http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx

Written by Mustafa Basgun

March 22, 2009 at 7:20 AM