Wednesday, April 30, 2008

Changing Asp.net configuration file programmatically

If you need to change the web.config file of your web site programatically ASP.net provides the WebConfigurationManager class to achive that task.

Here is a code piece that will allow you to change the culture settings in the web.config file.

I put this into the Application_Start method of Global.aspx.cs so that the web.confi is changed when the site is initialized. In order to prevent the web site from restarting over and over again, I need to check the value that I changed to see that it's there:

Configuration conf = WebConfigurationManager.OpenWebConfiguration("~");
SystemWebSectionGroup webSection = (SystemWebSectionGroup)conf.GetSectionGroup("system.web");
if (webSection.Globalization.Culture != MyConfiguration.Culture)
{
webSection.Globalization.Culture = MyConfiguration.Culture;
webSection.Globalization.UICulture = MyConfiguration.Culture;
conf.Save();
}

In this case above, I am changing the culture settings in the configuration file.

No comments: