0

我使用以下代码更改应用程序 Web 配置中的 appsetting 键值。

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)
    {
    }
}

我收到错误说明

试图执行未经授权的操作。

在保存配置更改的步骤中会引发此错误。

4

3 回答 3

0

我想你可能还需要AllowLocation在 file中设置machine.config。这是一个布尔值,指示是否可以使用该元素配置各个页面。如果“AllowLocation”为假,则不能在单个元素中进行配置。

更改 web.config 文件通常会导致应用程序重新启动。

如果您确实需要您的应用程序来编辑它自己的设置,那么您应该考虑一种不同的方法,例如将设置数据库化或使用可编辑的设置创建一个XML文件。

有关详细信息,请参阅 Stack Overflow 问题How do you modify the web.config appSettings at runtime? .

于 2013-06-24T07:22:56.967 回答
-1

我想这里你不需要写AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");

您可以使用 直接保存设置objConfig

试试这个代码:

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)
     {
     }
}
于 2013-06-24T07:26:17.170 回答
-1

MSDN 上的这篇文章可能有您正在寻找的答案:UnauthorizedAccessException when save AppSettings data to a Local Intranet file share

于 2013-06-24T07:17:49.500 回答