【问题标题】:C# update app.config elementC# 更新 app.config 元素
【发布时间】:2012-10-04 14:17:15
【问题描述】:

我有一个 WCF 服务器,它有以下 app.config 文件:

<?xml version="1.0"?>
<configuration>   
  <system.serviceModel>   
    <services>
      <service name="MyService" behaviorConfiguration="DiscoveryBehavior">       
        <endpoint address="net.tcp://192.168.150.130:44424/ServerService/"/>        
        <endpoint name="udpDiscovery" kind="udpDiscoveryEndpoint"/>
      </service>
    </services>
  </system.serviceModel> 
</configuration>

在另一台机器上安装时,我想让它使用该机器的地址自动更新地址。我有字符串,但我不明白如何更新 app.config 文件中的“地址”项。我有以下代码,但这不起作用:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.Settings["address"].Value = "new_value";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings"); 

我猜它不起作用,因为我没有名为“appSettings”的部分,但是如何访问该“地址”项?我尝试了不同的解决方案,但没有任何效果。

提前谢谢你。

【问题讨论】:

标签: c# wcf app-config


【解决方案1】:

我找到了一个可行的解决方案。读取内存中的整个文件,找到节点,替换值然后覆盖文件。这是在 OnStartup 方法上调用的,在我的程序初始化之前。

XmlDocument doc = new XmlDocument();
doc.Load("MyApp.exe.config");
XmlNodeList endpoints = doc.GetElementsByTagName("endpoint");
foreach (XmlNode item in endpoints)
{
    var adressAttribute = item.Attributes["address"];
    if (!ReferenceEquals(null, adressAttribute))
    {
        adressAttribute.Value = string.Format("net.tcp://{0}:44424/ServerService/", MachineIp);
    }
}
doc.Save("MyApp.exe.config");

【讨论】:

    【解决方案2】:

    我通常会删除密钥并将其重新添加以确保:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Remove("address");
            config.AppSettings.Settings.Add("address", "new_value");
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
    

    【讨论】:

    • 好的,但这不起作用,因为我不使用名为“AppSettings”的部分。这是一个自定义部分。
    猜你喜欢
    • 2012-10-28
    • 2019-01-06
    • 2014-03-23
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多