Wednesday, June 13, 2012

C# Windows Application Reading app.config file


In this post C# Windows Application Reading app.config file, we shall see on how to use the app.config file to store Application level constants and read then from a Windows application.

The app.config file in a Windows application is similar to the web.config file in an asp.net application, the app.config file can be used to store application level configuration settings like Database connection strings, File upload path, etc.

Unlike the web.config file the app.config file is not created automatically while creating a windows application, we need to add one, let us add it.

Right click the Project in the Solution Explorer selects Add -> New Item
In the list of templates which appear, select the Application Configuration File template
Click Add

A new file app.config will get added to the Project



 Open the app.config file, under the <configuration> tag add an <appSettings> tag and inside the <appSettings> tag add the list of items, here let us try to add a connection string add a connection string.

<configuration>
  <appSettings>
    <add key="ConnectionString" value="Data Source=<Your Server IP Here>\SQLEXPRESS;Initial Catalog=Employees;Integrated Security=True" />
  </appSettings>
</configuration>

Now we can access the connection string from the Windows form as follows.
In the form code, add a reference to System.Configuration

using System.Configuration;

Now add the below line of code to access the value of the ConnectionString key added to the app.config file.

string strConn = ConfigurationSettings.AppSettings["ConnectionString"].ToString();

Once this line is executed, the string strConn will hold the value of the connection string.

That’s it we have added a key value pair to the app.config file of a C# Windows application and read the value from a C# Windows form.

Search Flipkart Products:
Flipkart.com

1 comment:

k3 said...

Tanks mate.
Very clearly presented.