C#更新app.config元素
我有一个WCF服务器,它具有以下app.config文件:C#更新app.config元素,c#,wcf,app-config,C#,Wcf,App Config,我有一个WCF服务器,它具有以下app.config文件: <?xml version="1.0"?> <configuration> <system.serviceModel> <services> <service name="MyService" behaviorConfiguration="DiscoveryBehavior"> <endpoint addr
<?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>
我猜它不起作用,因为我没有名为“appSettings”的部分,但是如何访问“address”项呢?我尝试了不同的解决方案,但没有任何效果
提前谢谢。我通常会取下钥匙并重新添加,以确保:
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");
我通常会删除密钥并将其添加回,以确保:
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");
我找到了一个有效的解决方案。读取内存中的整个文件,找到节点,替换该值,然后覆盖该文件。在初始化程序之前,在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");
我找到了一个有效的解决方案。读取内存中的整个文件,找到节点,替换该值,然后覆盖该文件。在初始化程序之前,在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");
我认为这与我认为这与Ok相同,但这不起作用,因为我没有使用名为“AppSettings”的部分。这是一个自定义分区。好的,但这不起作用,因为我没有使用名为“AppSettings”的分区。这是一个自定义部分。