C# – Where should I put the connection strings for the class library and how to access them

cconnection-string

I have a solution with 4/5 projects.

I currently have the connection string for my domain project hardcoded in a c# file.

I'd like to put this in a web.config or something. From what I've been reading here and elsewhere I should store these connection strings in the web config of the calling application?

If so how do I access it?

When I do something like this in my class library:

ConnectionStringSettingsCollection connectionStrings =
    connectionStringsSection.ConnectionStrings;

The type or namespace could not be found, am I missing a reference or something?

Best Answer

You need to add a reference to System.Configuration in your main project.

then you can access connection string like this...

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;//<- last bit for a string version of the full connection string

ConfigurationManager will also let you access a number of other useful properties from your web.config file (this will also work for app.config files)

Related Topic