Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get multiple connection strings from web.config

How to get all the connection strings's names from the web.config via code in C#?

I tried this:

System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection x = webConfig.ConnectionStrings;
string here = x.SectionInformation.Name;
like image 393
petko_stankoski Avatar asked Apr 30 '12 13:04

petko_stankoski


People also ask

Where are connectionStrings in web config?

Connection strings go inside a <connectionStrings> element. The traditional place to put <connectionStrings> seems to be immediately before <appSettings> but its precise location shouldn't matter.

What is connection string providerName?

The providerName attribute is used to set the name of the .NET Framework data provider that the DataSource control uses to connect to an underlying data source. If no provider is set, the default is the ADO.NET provider for Microsoft SQL Server.

What is initial catalog in connection string in web config?

What is initial catalog in connection string in web config? Initial Catalog – The name of the Database. User Id – The User Id of the SQL Server. Password – The Password of the SQL Server.


2 Answers

This is how to use LINQ to get list of connection string names:

List<string> names = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .Select(v => v.Name)
    .ToList();

Or you can build a dictionary of it:

Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .ToDictionary(v => v.Name, v => v.ConnectionString);
like image 160
Sergei Zinovyev Avatar answered Sep 28 '22 10:09

Sergei Zinovyev


    foreach (ConnectionStringSettings c in System.Configuration.ConfigurationManager.ConnectionStrings)
    {
        //use c.Name
    }
like image 35
Tim S. Avatar answered Sep 28 '22 09:09

Tim S.