Write data into the web.config file using C#

Some times you may need to allow the end user to update the data into Asp.net or SharePoint web.config file . To do this you must ensure that the Network Service user (or the ASP.NET user on WinServer 2003 or earlier) has modify permissions on your website root folder.

If the permission is not correct you will get the following error:
An error occurred loading a configuration file: Access to the path ‘c:\inetpub\wwwroot\yourwebsitefolder\py39wsfg.tmp’ is denied.

Assuming you have setup the correct permissions this code below will allow your web app to write to the web.config file.

// update the SiteName tag in web.config with a new value
Configuration config = WebConfigurationManager.OpenWebConfiguration(“~”);
config.AppSettings.Settings[“SiteName”].Value = “New Site Name Value”;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.