0

I used the below code to change the appsetting key value in the web configuration of the application.

private void ChanngeDefaultPassword(string password)
{
    try
    {
        var objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
        AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
        objConfig.AppSettings.Settings["DEFAULT_PASSWORD"].Value = password;
        objConfig.Save();
    }
    catch (Exception ex)
    {
    }
}

I am getting error stating

Attempted to perform an unauthorized operation.

This error is thrown in the step to save the configuration changes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
smv
  • 477
  • 3
  • 11
  • 24

3 Answers3

0

I think you might also need to set AllowLocation in file machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "AllowLocation" is false, it cannot be configured in individual elements.

Changing the web.config file generally causes an application restart.

If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an XML file with the editable settings.

For details, see Stack Overflow question How do you modify the web.config appSettings at runtime?.

Community
  • 1
  • 1
Harikant
  • 269
  • 1
  • 6
-1

This article on MSDN may have the answer you're looking for: UnauthorizedAccessException when saving AppSettings data to a Local Intranet file share.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Micallef
  • 2,643
  • 7
  • 28
  • 36
-1

I think here you don't need to write AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");

You can save settings directly using objConfig.

Try this code:

private void ChanngeDefaultPassword(string password)
{
    try
    {
        System.Configuration.Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

        objConfig.AppSettings.Settings["DEFAULT_PASSWORD"].Value = password;
        objConfig.Save();
     }
     catch (Exception ex)
     {
     }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71