c# - 通过 C# 代码更新 web.config

标签 c# asp.net-mvc-5 web-config

我正在尝试通过我的 C# 代码在运行时更新一些配置设置。这是我的 web.config 部分

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="URL" value="google.com"/>
  <add key="Domain" value="d"/>
  <add key="Project" value="p"/>
  </appSettings>

这是我正在使用的代码:

Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
System.Configuration.ConfigurationManager.AppSettings.Remove("URL");
System.Configuration.ConfigurationManager.AppSettings.Add("URL","www.stackoverflow.com");
config.Save();

但是,它给出了我的配置文件是只读的错误。 我正在使用 Visual Studio 2013。 我应该如何解决这个问题?

最佳答案

请你试试这个好吗?

protected void EditConfigButton(object sender, EventArgs e)
{
   Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
   AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
   //Edit
   if (objAppsettings != null)
   {
      objAppsettings.Settings["test"].Value = "newvalueFromCode";
      objConfig.Save();
   }
}

或者请引用链接Editing Web.config programatically

关于c# - 通过 C# 代码更新 web.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31134145/

相关文章:

C# 创建其他应用程序可以看到的系统事件

c# - 窗体 Visual C# 中的控制台

asp.net-mvc-5 - 如何让 Glimpse 与 EF6 一起工作?

c# - 如何使用 Razor 在主视图 View 模型中保存部分 View View 模型项?

ASP.NET 4.5 Web.config 错误

C#/.NET : FInd out whether a server exists, 为 SVC 记录查询 DNS

c# - Linq 左连接多个表

asp.net-mvc-5 - 电子邮件不能为空。 MVC 5,身份2.0.0

asp.net - Microsoft 重写模块 - 在 url 上强制 www 或从 url 中删除 www

asp.net - 更改 Web.config 连接字符串而不重置 session