【问题标题】:How can I change the value of a custom configSections variable?如何更改自定义 configSections 变量的值?
【发布时间】:2019-01-15 07:08:16
【问题描述】:

我的 App.config 文件的 configSections 中有一个自定义部分,如何在代码中更改此部分的变量之一的值?

我要更改的部分是“serverConfiguration”,我想更改“serverUrl”的值:

<?xml version="1.0" encoding="utf-8"?>
 <configuration>
  <configSections>
   <section name="serverConfiguration" type="someType" />
  </configSections>
    <serverConfiguration serverUrl="http://development/server/" />
</configuration>

我从上一个问题App.Config change value 中找到了这段代码。 它看起来接近我需要的东西,但我不确定如何自己更改它以将其用于自定义部分而不是 AppSettings。下面的代码是否适用于我正在尝试做的事情?如何更改下面的代码以允许我将此新字符串作为 serverUrl "http://staging/server/" 传递?谢谢!

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}

【问题讨论】:

    标签: c# app-config


    【解决方案1】:

    您可以选择将配置加载到 XML 中,编辑节点值并将其保存回来。试试这个

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);          
    
            xmlDoc.SelectSingleNode("//serverConfiguration").Attributes["serverUrl"].Value = "http://staging/server/";
            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    

    保存文件后刷新配置部分可能是个好主意。

    ConfigurationManager.RefreshSection

    【讨论】:

    • 效果很好,非常感谢!我之前使用过 XML 文档的 Load,但没想到在这种类型的应用程序中使用它。
    猜你喜欢
    • 2013-01-14
    • 2018-02-08
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多