如何获取配置文件的ConnectionString名称

时间:2011-01-16 18:19:30

标签: c#

我可以从配置文件中读取connectionstring / s但是我需要获取与连接字符串相关联的元素名称

实施例

<connectionStrings>
<add 
  name="LocalSqlServer" 
  connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
  providerName="System.Data.SqlClient"   />
 </connectionStrings>

我需要从connectionString

中获取LocalSqlServer

3 个答案:

答案 0 :(得分:16)

根据documentation,它应该像这样工作:

ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;

if (connections.Count != 0)
{
    foreach (ConnectionStringSettings connection in connections)
    {
        string name = connection.Name;
    }
}

答案 1 :(得分:3)

使用

ConfigurationManager.ConnectionStrings[0].Name

答案 2 :(得分:2)