How to read from and write to the web.config file using C#

To read from a Web.Config file using C# is very easy to do. Let's say we have an appSettings tag in our Web.Config that holds the website title. Inside in our web.config you would have something like this:


   

To get .net to read this value all you need to do is add this to your code behind page on your site. Be sure to add the System.Web.Configuration namespace as this is not added by default.

using System.Web.Configuration;

//read in the SiteName tag from web.config
string MySiteName = WebConfigurationManager.AppSettings["SiteName"];

If you want more details on how to read from web.config please see my earlier post here

You might also want to write to your web.config file to allow the end user to update this data. To do this you must ensure that the Network Service user (or the ASP.NET user on WinServer 03 or earlier) has modify permissions on your website root folder.

Without the correct permission you will get the following error if you try to add the code below:
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");

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets