Eric Herlitz
Eric Herlitz

Reputation: 26307

Grabbing connectionStrings from web.config based on the providername

Im trying to figure out how to grab all connectionStrings from a web.config that has a certain provider but got stuck.

The basics of my method looks like this

var webConfig = new ExeConfigurationFileMap { ExeConfigFilename = GlobalSettings.FullpathToRoot + "web.config" };
var config = ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None);
var section = (ConnectionStringsSection)config.GetSection("connectionStrings");

// some code like 
foreach(var item in section.providerName.equals("sql.provider"))
...

Any advice is highly appreciated!

Upvotes: 1

Views: 1616

Answers (1)

Eric Herlitz
Eric Herlitz

Reputation: 26307

Solved the issue

public static Dictionary<string,string> ExistingConnections()
{
    var connections = new Dictionary<string, string>();
    foreach (ConnectionStringSettings connection in ConfigurationManager.ConnectionStrings)
    {
        if(connection.ProviderName == "sql.providername")
            connections.Add(connection.ProviderName, connection.ConnectionString);
    }
    return connections.Count > 0 ? connections : null;
}

or by using linq

public static Dictionary<string,string> ExistingConnections()
{
    var connections = ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>().Where(connection => connection.ProviderName == "Camelot.SharePointProvider").ToDictionary(connection => connection.ProviderName, connection => connection.ConnectionString);
    return connections.Count > 0 ? connections : null;
}

Upvotes: 1

Related Questions