Connection String in the Application Configuration File

Connection String in the Application Configuration File

Application configuration files contain settings that are specific to a particular application. For example, an ASP.NET application can have one or more web.config files, and a Windows application can have an optional app.config file. Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file.

connectionStrings section supports the <add>, <remove>, and <clear> tags.

 

<configuration>

  <connectionStrings>

    <clear />

    <add name="myConnectionString"

         connectionString="Data Source=mySQLServer;Initial Catalog=myDatabase;User ID=myUserID;Password=myPassword"

         providerName="System.Data.SqlClient" />

  </connectionStrings>

</configuration>

In this example it first clears the list of connection settings  then adds a new connection string setting called myConnectionString. You can access the connection strings in code by using the static ConnectionStrings collection on the ConfigurationManager class (implemented in the System.Configuration.dll assembly).

Following code sample shows how to access Connection string in code:

 

String strConnectionString= ConfigurationManager.ConnectionStrings["myConnectionString"].ToString();

SqlConnection connection = new SqlConnection(strConnectionString);



Ebook Download
View all
Learn
View all