My Blog

Custom Configuration Settings in App.Config (part 1)

by lupok on martedì 15 gennaio 2013 16:02
UrlSection.cs
using System;
using System.Configuration;
 
 
// Define a custom section. 
// This class shows how to use the ConfigurationPropertyAttribute. 
public class UrlsSection : ConfigurationSection
{
   [ConfigurationProperty("name", DefaultValue = "Contoso",
       IsRequired = true, IsKey = true)]
   public string Name
   {
      get
      {
         return (string)this["name"];
      }
      set
      {
         this["name"] = value;
      }
   }
 
   [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com",
       IsRequired = true)]
   [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
   public string Url
   {
      get
      {
         return (string)this["url"];
      }
      set
      {
         this["url"] = value;
      }
   }
 
   [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
   [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
   public int Port
   {
      get
      {
         return (int)this["port"];
      }
      set
      {
         this["port"] = value;
      }
   }
}
UsingConfigurationPropertyAttribute.cs
using System;
using System.Configuration;
 
public class UsingConfigurationPropertyAttribute
{
 
   // Create a custom section and save it in the  
   // application configuration file. 
   static void CreateCustomSection()
   {
      try
      {
 
         // Create a custom configuration section.
         UrlsSection customSection = new UrlsSection();
 
         // Get the current configuration file.
         System.Configuration.Configuration config =
                 ConfigurationManager.OpenExeConfiguration(
                 ConfigurationUserLevel.None);
 
         // Add the custom section to the application 
         // configuration file. 
         if (config.Sections["CustomSection"] == null)
         {
            config.Sections.Add("CustomSection", customSection);
         }
 
 
         // Save the application configuration file.
         customSection.SectionInformation.ForceSave = true;
         config.Save(ConfigurationSaveMode.Modified);
 
         Console.WriteLine("Created custom section in the application configuration file: {0}",
             config.FilePath);
         Console.WriteLine();
 
      }
      catch (ConfigurationErrorsException err)
      {
         Console.WriteLine("CreateCustomSection: {0}", err.ToString());
      }
 
   }
 
   static void ReadCustomSection()
   {
      try
      {
         // Get the application configuration file.
         System.Configuration.Configuration config =
                 ConfigurationManager.OpenExeConfiguration(
                 ConfigurationUserLevel.None) as Configuration;
 
         // Read and display the custom section.
         UrlsSection customSection =
             config.GetSection("CustomSection"as UrlsSection;
         Console.WriteLine("Reading custom section from the configuration file.");
         Console.WriteLine("Section name: {0}", customSection.Name);
         Console.WriteLine("Url: {0}", customSection.Url);
         Console.WriteLine("Port: {0}", customSection.Port);
         Console.WriteLine();
      }
      catch (ConfigurationErrorsException err)
      {
         Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
      }
 
   }
 
   static void Main(string[] args)
   {
 
      // Get the name of the application. 
      string appName =
          Environment.GetCommandLineArgs()[0];
 
      // Create a custom section and save it in the  
      // application configuration file.
      CreateCustomSection();
 
      // Read the custom section saved in the 
      // application configuration file.
      ReadCustomSection();
 
      Console.WriteLine("Press enter to exit.");
 
      Console.ReadLine();
   }
}

The following is an excerpt of the configuration file containing the custom section as defined in the previous sample.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="CustomSection" type="UrlsSection, UsingConfigurationPropertyAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </configSections>
    <CustomSection name="Contoso" url="http://www.contoso.com" />
</configuration>


CustomAppConfig.zip

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags