Tuesday, August 2, 2011

Create Section in the Configure file and Read Parameters from it

Create section in config file is pretty much like:
< ? xml version="1.0" encoding="utf-8" ?> 
<configuration>
  <configSections>
    <section name="InstrumentationSettings" type="System.Configuration.NameValueFileSectionHandler" />
  < /configSections>
  < ! -- < InstrumentationSettings file="instrumentation.xml"  /> --> 
  <InstrumentationSettings>
    <add key="MachineName" value="EMC01" />
    <add key="UserID" value="03" />
    <add key="CPU" value="2.8G" />
    <add key="Memory" value="2G" />
  < /InstrumentationSettings> configuration>

To Read the information, the code is pretty much like:

using System; using System.Collections.Specialized; 
using System.Configuration;        
internal class Program     
{         
       private static void Main(string[] args)         
      {        
          var instSettings = ConfigurationManager.GetSection("InstrumentationSettings") as NameValueCollection;            
            if (null != instSettings)
            {               
               Console.WriteLine(instSettings["MachineName"]);
            }
        }
}
Similar code like:
                    
 Dictionary< string,string >  instSettingsDict = new Dictionary< string, string >();
            if (null != instSettings)
            {
                for (int i = 0; i < instSettings.Count; i++)
                {
                 instSettingsDict.Add(instSettings.Keys[i], instSettings[instSettings.Keys[i]]);
                }
            }

No comments: