Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get ConnectionString Name from config file

Tags:

c#

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.

like image 638
user9969 Avatar asked Jan 16 '11 18:01

user9969


2 Answers

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;
    }
}
like image 166
Martin Buberl Avatar answered Oct 14 '22 02:10

Martin Buberl


Use

ConfigurationManager.ConnectionStrings[0].Name
like image 31
Aliostad Avatar answered Oct 14 '22 02:10

Aliostad