【问题标题】:How I can change the applicationSettings in my web.config via C#如何通过 C# 更改 web.config 中的 applicationSettings
【发布时间】:2012-12-24 16:43:47
【问题描述】:

我想通过 C# 更改 web.config。

我的网站配置

 <?xml version="1.0" encoding="utf-8"?>

    <!--
      Weitere Informationen zum Konfigurieren der ASP.NET-Anwendung finden Sie unter
      "http://go.microsoft.com/fwlink/?LinkId=169433"
      -->

    <configuration>
        <configSections>
            ...
        </configSections>
        <system.web>
            ...
        </system.web>

        <applicationSettings>
            <AdminTest.Properties.Settings>
                <setting name="AD_Admin" serializeAs="String">
                    <value>GastzugangAdmin</value>
                </setting>
                <setting name="AD_User" serializeAs="String">
                    <value>GastzugangUser</value>
                </setting>
            </AdminTest.Properties.Settings>
        </applicationSettings>
    </configuration>

使用字符串ADAdmin = Properties.Settings.Default.AD_Admin; 可以从web.config 获取值,但我不知道如何覆盖它。我试试这个。

protected void btnCon_Click(object sender, EventArgs e)
        {
            string con = txtCon.Text;

            try
            {
                ConfigurationManager.AppSettings.Set("AD_Admin", con);
                Settings.Default.Save();

            }
            catch (Exception)
            {

            }

        }

但我不工作。

【问题讨论】:

标签: c# asp.net configuration web-config application-settings


【解决方案1】:

.NET Fx 中有配置 API 用于修改配置,您可以使用相同的。例如检查WebConfigurationManager

var config = WebConfigurationManager.OpenWebConfiguration("~/web.config");
config.AppSettings["xyz"] = value;
config.Save();

请注意,只要您保存配置,您的 Web 应用程序就会重新启动。

【讨论】:

  • 对 System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty] 的访问由于安全级别而不起作用:(
  • @Tarasov,试试config.AppSettings.Settings["xyz"] = value。顺便说一句,运行您的代码的用户帐户也需要对 web.config 文件具有读/写权限。
猜你喜欢
  • 1970-01-01
  • 2015-09-21
  • 2010-10-27
  • 2012-10-28
  • 1970-01-01
  • 2011-02-03
  • 2011-11-08
  • 2011-04-18
  • 2012-01-31
相关资源
最近更新 更多