12

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;

3 Answers 3

28
    foreach (ConnectionStringSettings c in System.Configuration.ConfigurationManager.ConnectionStrings)
    {
        //use c.Name
    }
Sign up to request clarification or add additional context in comments.

2 Comments

You can read more about System.Configuration.ConfigurationManager.ConnectionStrings at MSDN.
Get connection string from machine.config too. Not only web.config.
7

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);

Comments

0

Not specific to Connection Strings, but might be helpful none the less.

System.Web.HttpContext ctx = System.Web.HttpContext.Current;

Configuration config;

if (ctx != null)
    config = WebConfigurationManager.OpenWebConfiguration(ctx.Request.ApplicationPath);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.