Updating the Configuration file settings from code behind.


In this article we will discuss how can we access the configuration files section in the code behind pages and then how can we do the changes in the sections we read. In this article I will show you how to update the Sessionstate, compilation and the themes settings in web.config from code behind.

Suppose in the web configuration file we have done below settings:


<sessionState timeout="30"/>
<compilation debug="true" targetFramework="4.0">
</compilation>
<pages theme="TestTheme">
</pages>


Now in the design page we will take three buttons one each for sessionstate , compilation
debug and themes settings.Now on the button clicks we will access the configuration file
using WebConfigurationManager and then perform the changes.

Note:

WebConfigurationManager will access the configuration file.
OpenWebConfiguration will open the configuration file.
GetSection will allow us to access the specific section.


protected void btn_setsessionstate_Click(object sender, EventArgs e)
{
Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
SessionStateSection sc = (SessionStateSection)c.GetSection("system.web/sessionState");
sc.Timeout = new TimeSpan(0, 0, 30, 0, 0);
c.Save();
lblmessage.Text = "Session timeout set";

}
protected void btn_setcompilationdebug_Click(object sender, EventArgs e)
{
Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
CompilationSection cs = (CompilationSection)c.GetSection("system.web/compilation");
if (cs.Debug)
{
cs.Debug = false;
}
else
{
cs.Debug = true;
}
c.Save();
lblmessage.Text = "Compilation debug set";
}
protected void btn_setglobaltheme_Click(object sender, EventArgs e)
{
Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
PagesSection ps = (PagesSection)c.GetSection("system.web/pages");
ps.Theme = "TestTheme";
c.Save();
lblmessage.Text = "Global theme set";
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: