In software applications, there are sometimes several values, that need to be changed sometimes, like database connection information, API access credential information, directory path etc. I am talking about both desktop and web applications. In the case of C#.NET applications, there is a default XML file for putting such settings values, it’s “web.config” for Web applications and “app.config” for desktop applications. If we don’t put those dynamic values here, we would have to compile the applications every time we need to change them!!
This is especially a big issue in the case of product-level developments, which are distributed to customers and each customer sets different values. Although many codes can be used without compiling like an asp.net website or a PHP web application, still using hard-coded settings is a terrible thing, for other new developers to that application also where he has to find those inside the core code. There are a lot of others disadvantages too. I will strictly recommend using an external file for storing those app settings(either on a text/XML file or if even a code file, should be dedicated to configuration settings only).
Microsoft .NET platform provides a very easy and efficient way to manage these application settings. By default, a “.config” file is associated with every new desktop/web project. This file is in xml formatting which are serialized/deserialized in c# objects automatically. In this small tutorial, I will try to show you how to use and retrieve these configuration values(on “app.config” or “web.config”) from a config file in c# code examples. I will use the term ‘config file’ to refer to ‘app.confg/web.config’.
Settings Values On Config File In C# Project:
There are generally two kinds of scenarios, First, you want to store only a single value for a specific setting. Second, you need a couple of values to set for a specific setting. You should use two different kinds of ways to meet these needs.
Single Value Settings:
To store a single value, you should put it inside the ‘<appSettings>’ section. As follows:
<appSettings>
<add key="SettingKey1" value="Settings 1 Value"/>
<add key="SettingKey2" value="Settings 2 Value"/>
</appSettings>
[/code]
Code language: HTML, XML (xml)
Retrieving these values is pretty straightforward; use as like following code snippet where you need it:
string value1 = ConfigurationManager.AppSettings["SettingKey1"];
string value2 = ConfigurationManager.AppSettings["SettingKey2"];
Code language: JavaScript (javascript)
use should have ‘System.Configuration’ name space in that code file. You can also use ‘WebConfigurationManager’ instead of ‘ConfigurationManager’ with the namespace ‘System.Web.Configuration’ in case of asp.net web application.
Multiple Value Settings:
To store more than one value in a specific setting, you should use ‘<configSections>’ section. You will need the following parts implemented:
- Add a section name and its class name(with namespace) in the <sectionConfigs> area in the config file.
- Add a new tag with a section names with different attribute names and their values in the config file.
- Implement a class that extends ConfigurationSettings class.
Here is a sample code for the config file:
<configSections>
<section name="mySettings1" type="myProject.Libraries.MySettings1"/>
<section name="mySettings2" type="myProject.Libraries.MySettings2"/>
</configSections>
<mySettings1
key1="Key 1 value"
key2="Key 2 value"
/>
<mySettings2
key1="Key 1 value"
key2="Key 2 value"
/>
Code language: HTML, XML (xml)
Here are a few things to remember in this stage:
- It should be at the beginning of all others configurations.
- Custom tag name must match the name of the section
The class file should contain some getter setters, the same number of the attribute names for a section, like as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
namespace myMVC.Libraries.FB
{
public class MySettings : ConfigurationSection
{
[ConfigurationProperty("key1", IsRequired = true)]
public string Key1
{
get
{
return (string)this["key1"];
}
}
}
}
Now we are all set to use those settings from our application. Just use like following code samples when you want to retrieve those values:
var settings = ConfigurationManager.GetSection("mySettings");
MySettings current;
if (settings != null)
{
current = settings as MySettings;
string valueToUse = current.ApiKey;
//use the value
}
Code language: JavaScript (javascript)
With this, you can store multiple values for a specific setting in a separate section on the configuration file. And of course, you won’t have to recompile your application while changing these values
as this is being read on run time when needed. So, if you are working on a .NET application, you should always use this configuration file for storing dynamic settings values instead of using it as hard-coded and on any other kind of file like .txt files etc. Happy coding 🙂
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
tushar rana says
thanx RANA.,JAY RANA.
M.S.Patil says
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class datagrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//SqlConnection conn = new SqlConnection(“data source=localhost\\sqlexpress;Initial Catalog=patil;Integrated Security=SSPI”);
string con = ConfigurationManager.ConnectionStrings[“patil”].ConnectionString;
SqlConnection conn = new SqlConnection(con);
string sqlsrting = “spr_displaydata”;
SqlCommand cmd = new SqlCommand(sqlsrting, conn);
SqlDataAdapter Dataadpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
Dataadpt.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
WEB.CONFIG File:
M.S.Patil says
what about windows development?
fam says
In order to get this working I had to add the namespace in the ConfigSections of the config file:
Shaji George says
Could you please show the sample config file after you added the namespace in the ConfigSections?
charitha says
I am using a .bat file in c# code. i have hard coded that path in code. i want to give the path in .config in order to run it in IIS server. Could you please help me?
Shaji George says
When I try your sample
var settings = ConfigurationManager.GetSection(“mySettings”);
MySettings current;
if (settings != null)
{
current = settings as MySettings;
string valueToUse = current.ApiKey;
//use the value
}
the ‘seetings’ variable is always null. How do I fix it?
paul says
no pblim
paul says
hi, can u use in this php
Bob says
Yes Paul, you can use this in PHP. Just copy and paste the code into the code file, it should work perfect for you.
Neha says
Hi…Can we save app.config by different extension like app.xml and use ConfigurationManager to access it