我试图找出如何从具有某个提供商但仍然卡住的web.config中获取所有connectionStrings。
我方法的基础知识就像这样
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"))
...
非常感谢任何建议!
答案 0 :(得分:1)
解决了问题
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;
}
或使用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;
}