Connection string from app.config in windows application

Connection string from app.config in windows application

2 Comments

In windows application configuration file, connection strings for your database can be stored as key/value pairs in the connectionStrings section of the configuration element.

<configuration>
	<connectionStrings>
		<add name="MyDBConnection" connectionString="Server=xxxx; UID=xxxx; PWD=xxxx; Database=xxxx;"/>
	</connectionStrings>
</configuration>

To access your connection string from the configuration file you need to use the following code.

string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;

The ConfigurationManager class in included with in the System.Configuration namespace.

using System.Configuration;

After the using statement included, compiler says that

“The name ‘ConfigurationManager’ does not exist in the current context”.

To resolve this problem you need to add reference to “C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\System.configuration.dll” using following steps.

Goto Project -> Add References…
Switch to .Net tab in ‘Add Reference’ window, and select System.Configuration and click OK to add refernce in your project.

Now the connection string from app.config file will be accessed using above code.

About the author:

Tags:

2 Comments

  1. Nitin  - June 4, 2014 - 5:16 PM
    Reply /

    Thanks for the help, I forget to add reference in my project but your answer showed me right way. Thanks…

Leave a comment

Socials

Newsletter

Back to Top