Read a configuration section from web.config

Suresh.mekkattil
Posted by Suresh.mekkattil under ASP.NET category on | Points: 40 | Views : 2703
Consider we have a section in our web.config file as follow

		<SampleConfig Name="Scott" Address="Address1" Email="Email@domain.com" />

and we want to read this from our C# code and then return a object of person class as follow:


public class Person
{
public Person()
{

}

public string Name
{
get;
set;
}

public string Address
{
get;
set;
}

public string Email
{
get;
set;
}


For that, we first need to create a section handler class as follows:

public class SampleSectionConfiguration : ConfigurationSection
{
public const string SECTION_NAME = "SampleConfig";
public const string NAME = "Name";
public const string ADDRESS = "Address";
public const string EMAIL = "Email";

[ConfigurationProperty(NAME, IsRequired = true)]
public string Name
{
get
{
return this[NAME].ToString();
}
set
{
this[NAME] = value;
}
}

[ConfigurationProperty(ADDRESS, IsRequired = true)]
public string Address
{
get
{
return this[ADDRESS].ToString();
}
set
{
this[ADDRESS] = value;
}
}

[ConfigurationProperty(EMAIL, IsRequired = true)]
public string Email
{
get
{
return this[EMAIL].ToString();
}
set
{
this[EMAIL] = value;
}
}


public static Person GetPersonConfiguration()
{
Person person = new Person();
SampleSectionConfiguration section = (SampleSectionConfiguration)ConfigurationHelper.GetSection(SECTION_NAME);
person.Address = section.Address;
person.Email = section.Email;
person.Name = section.Name;
return person;
}

private static Configuration ConfigurationHelper
{
get
{
return WebConfigurationManager.OpenWebConfiguration("~/");
//IServiceProvider serviceProvider = null;
//IWebApplication webApp = (IWebApplication)serviceProvider.GetService(typeof(IWebApplication));
//return webApp.OpenWebConfiguration(true);
}

}

}

Then configure your custom configuration section as follow:

<section name="SampleConfig" type="SectionConfig.SampleSectionConfiguration, SectionConfig, Culture=Neutral, PublicTokenKey=null"/>

Then put the code in your aspx file as follows:

public static Person GetPerson()
{
return SectionConfig.SampleSectionConfiguration.GetPersonConfiguration();
}

Comments or Responses

Login to post response