CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Development Utilizing Config File In C#.NET Application

Utilizing Config File In C#.NET Application

Rana Ahsan December 18, 2010 11 Comments


 Utilizing Config File In C#.NET Application    

In a 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 case of C#.NET applications, there are a default XML file for putting such settings values, its web.config for Web application and app.config for desktop applications. If we don’t put those dynamic values here, we would had to compile the applications every time we need to change it!!!!

This is specially a big issue in case of product level developments, which are distributed to customers and each customer sets different values. Although many code can used without compiling like asp.net website or a php web application, but still using hard-coded settings is a terrible things, to other new developers to that application also where he has to find those inside the core code. There are a lot others disadvantages too. Simply, I will strictly recommend to use an external file for storing those app settings(either on a text/xml file, or if even a code file, should be dedicated for configurations settings only).

Microsoft .NET platform provide 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 config file in c# code examples. I will use term ‘config file’ to refer to ‘app.confg/web.config’.

Settings Values On Config File In C# Project:

There are generally two kinds of scenario, First, you want to store only a single value for a specific settings. Second, you need a couple of values to set for a specific settings. You should use two different kind of ways to meet these needs.

Single Value Settings:
To store a single value, you should put it inside ‘<appSettings>’ section. Like as follows:

<appSettings>
    <add key="SettingKey1" value="Settings 1 Value"/>
    <add key="SettingKey2" value="Settings 2 Value"/>
</appSettings>

Retrieving these values are pretty straight forward, just use as like following code snippet where you need it:

string value1 =  ConfigurationManager.AppSettings["SettingKey1"];
string value2 =  ConfigurationManager.AppSettings["SettingKey2"];

use should have ‘System.Configuration’ name space in that code file. You can also use ‘WebConfigurationManager’ instead of ‘ConfigurationManager’ with namespace ‘System.Web.Configuration’ in case of asp.net web application.

Multiple Value Settings:
To store more than one values in a specific settings, you should use ‘<configSections>’ section. You will need the following parts implemented:

  • Add a section name and its class name(with name space) in the <sectionConfigs> area in the config file.
  • Add new tag with section name with different attribute names and their values in the config file.
  • Implement a class that extends ConfigurationSettings class.

Here is 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"
 />

Few things to remember in this stage:

  • Should be at the beginning of all others configurations.
  • Custom tag name must match the name of section

The class file should contain some getter setters , 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
 }

With this, you can store multiple values for a specific settings in a separate section on the configuration file. And of course, you won’t have to recompile you application while changing these values
as this are being read on run time when needed. So, if you are working on a .NET application, you should definitely always use this configuration file for storing dynamic settings values instead of using
as hard-coded and on any other kind of file like .txt files etc. Happy coding 🙂

Related

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

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Facebook C# API Tutorials
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Tutorial On Uploading File With CodeIgniter Framework / PHP
  • Utilizing Config File In C#.NET Application
  • Using GIT Plugin For Netbeans IDE

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in