【问题标题】:Is there any way to update the Web.config file in asp.net through .cs or .aspx page [duplicate]有没有办法通过.cs或.aspx页面更新asp.net中的Web.config文件[重复]
【发布时间】:2015-06-24 10:46:42
【问题描述】:

我需要通过 .aspx 或 .cs 页面更改 ASP.Net 中 web.config 文件中的 appSettings 值。有没有可能> 请提供一些例子,我的示例代码是:

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="variable" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

【问题讨论】:

  • 抱歉,stackoverflow 是针对“我所拥有的有什么问题”......而不是“请给我工作代码”。你看过使用inbuilt .NET XML classes吗?
  • 虽然技术上可行,但您应该考虑另一种方法有几个原因:运行应用程序池的帐户不应有权更改 Web 应用程序目录中的文件。此外,一旦写入 web.config 文件,应用程序池将被回收。这将影响应用程序的所有用户。
  • 也阅读ConfigurationManager类。

标签: c# asp.net web-config


【解决方案1】:

基于此thread

 Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
  myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text;
  myConfiguration.AppSettings.Settings.Remove("MyVariable");
  myConfiguration.AppSettings.Settings.Add("MyVariable", "MyValue");
  myConfiguration.Save();

【讨论】:

    【解决方案2】:

    是的,这是可能的,但应该谨慎行事。我必须在其中执行此操作的示例是安装程序项目的一部分,因此 web.config 未使用,并且该应用程序是第一次安装。

    这样的东西可以根据您的目的进行调整:

    private string ConfigPath { get { return Path.Combine(targetDirectory.Substring(0, targetDirectory.LastIndexOf("\\") - 1), "Web.Config"); } }
    
    XmlDocument doc = new XmlDocument();
    doc.Load(this.ConfigPath);
    
    XmlNode MyNode = doc.SelectSingleNode("configuration/appSettings/add[@key='YourKey']");
    MyNode.Attributes["value"].Value = YourValue;
    
    doc.Save(this.ConfigPath);
    

    您也可以像这样使用 ConfigurationManager 来修改现有密钥:

    var config = System.Web.Configuration.WebConfigurationManager
          .OpenWebConfiguration("~/web.config");
    config.AppSettings.Settings["Your Key"].Value = "Your Value";
    config.Save(ConfigurationSaveMode.Modified);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-23
      • 2012-12-04
      • 2017-07-10
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 2010-09-12
      相关资源
      最近更新 更多