Monday, February 9, 2009

ASP.NET - How to add value to appSettings in Web.Config

We can save some data in Web.Config with a key and its related value, but it's important to know that this place is not our database to keep a lot of data there.

Configuration class make it able to add the key and value pair of data, then it saves them in pre-opened web configuration file.

In the following example, we have two textbox controls which user can enter the key and value and add them to the Web.Config file if they are not empty.

using System.Configuration;
using System.Web.Configuration;
...
  if(txtKey.Text == String.Empty ||
      txtVal.Text == String.Empty)
     return;

  Configuration cnfg =
     WebConfigurationManager.OpenWebConfiguration("~");
  cnfg.AppSettings.Settings.Add(txtKey.Text,txtVal.Text);
  cnfg.Save();
...

Share/Bookmark

No comments: