• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Utilizing Config File In C#.NET Application

Utilizing Config File In C#.NET Application

December 18, 2010 by Rana Ahsan 11 Comments

C#.NET Tutorials

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: .net, c#, web application

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. tushar rana says

    February 9, 2012 at 10:43 am

    thanx RANA.,JAY RANA.

    Reply
  2. M.S.Patil says

    July 27, 2012 at 10:07 am

    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:

    Reply
  3. M.S.Patil says

    July 27, 2012 at 10:09 am

    what about windows development?

    Reply
  4. fam says

    December 4, 2014 at 4:26 pm

    In order to get this working I had to add the namespace in the ConfigSections of the config file:

    Reply
    • Shaji George says

      July 29, 2015 at 10:59 am

      Could you please show the sample config file after you added the namespace in the ConfigSections?

      Reply
  5. charitha says

    May 4, 2015 at 8:01 am

    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?

    Reply
  6. Shaji George says

    July 29, 2015 at 11:00 am

    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?

    Reply
    • paul says

      April 4, 2016 at 7:19 am

      no pblim

      Reply
  7. paul says

    April 2, 2016 at 12:35 am

    hi, can u use in this php

    Reply
    • Bob says

      April 8, 2016 at 1:57 pm

      Yes Paul, you can use this in PHP. Just copy and paste the code into the code file, it should work perfect for you.

      Reply

Trackbacks

  1. C# Tutorial For Retrieving Facebook Api Access Token | codesamplez.com says:
    January 4, 2011 at 3:47 am

    […] code sample, structure of MySettings class is being created from the idea of my another article on storing application settings using c#, so either go through that to get the clear idea and use the best practice, or you can hard code […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • LinQ To SQL Database Update Operations In C#
    LinQ To SQL Database Update Operations In C#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023