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!
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;
}
精彩评论