Tuesday, December 21, 2010

Creating Custom Sections in App.Config File

/////Config File////
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

    <section name ="Application" type="CustomSectionsExample.MyHandler, CustomSectionsExample"/>
  </configSections>
  <Application>
    <Name>POWERPNT</Name>
    <Runtime>1</Runtime>
    <Message>Say Hey to Word application</Message>
    <MessageTime>1</MessageTime>
  </Application >
 
</configuration>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Create Custom Handler
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.Configuration;

namespace CustomSectionsExample
{
    public class MySettings
    {
        public string Name;
        public MySettings()
        {
        }
    }
   public  class MyHandler: IConfigurationSectionHandler
    {
        public MyHandler()
        {
          
           
        }
       
      
       

        #region IConfigurationSectionHandler Members

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            MySettings Settings = new MySettings();
            Settings.Name = section.SelectSingleNode("Name").InnerText;
            return Settings;
        }

        #endregion
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Finally Read from App.Config
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace CustomSectionsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MySettings settings = (MySettings)ConfigurationManager.GetSection("Application");
            Console.WriteLine(settings.Name);
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment