9

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.

3 Answers 3

19

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

No OP wants to get LocalSqlServer.
Yeah, i saw that a second after my answer. I changed it.
3

Use

ConfigurationManager.ConnectionStrings[0].Name

1 Comment

If ConfigurationManager is not available for you, you could add it by right clicking References>Add Reference and adding System.Configuration
2

You access it programmatically through the API.

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.