简体   繁体   中英

How can I get ConnectionString Name from config file

I can read the connection strings from the config file, however I need to get the element name that is associated with connection string.

Example

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

I need to get LocalSqlServer out of the connectionString.

According to the documentation it should work like this:

ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;

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

使用

ConfigurationManager.ConnectionStrings[0].Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM