如何通过C#中的代码从web.config获取所有连接字符串的名称?
我试过了:
System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection x = webConfig.ConnectionStrings;
string here = x.SectionInformation.Name;
答案 0 :(得分:25)
foreach (ConnectionStringSettings c in System.Configuration.ConfigurationManager.ConnectionStrings)
{
//use c.Name
}
答案 1 :(得分:4)
这是使用LINQ获取连接字符串名称列表的方法:
List<string> names = ConfigurationManager.ConnectionStrings
.Cast<ConnectionStringSettings>()
.Select(v => v.Name)
.ToList();
或者您可以构建它的字典:
Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
.Cast<ConnectionStringSettings>()
.ToDictionary(v => v.Name, v => v.ConnectionString);
答案 2 :(得分:0)
不是特定于连接字符串,但可能会有所帮助。
System.Web.HttpContext ctx = System.Web.HttpContext.Current;
Configuration config;
if (ctx != null)
config = WebConfigurationManager.OpenWebConfiguration(ctx.Request.ApplicationPath);