gpt4 book ai didi

c# - RefreshSection 未按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:40 26 4
gpt4 key购买 nike

我正在尝试更新正在运行的应用程序的 app.config 文件。更新确实有效(即文件得到更新),但是当我重新读取文件时,它显示旧值。 this的答案问题确实暗示 app.config 已缓存,但调用 RefreshSection 应该强制重新读取。

这是 app.config(直接来自 MS 示例):

<configuration>      
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ICalculator" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8000/ServiceModelSamples/Service/CalculatorService"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator"
contract="ServiceReference1.ICalculator" name="WSHttpBinding_ICalculator">
<identity>
<userPrincipalName value="migree@redmond.corp.microsoft.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>

这是我用来更新它的控制台应用程序的代码:

static void Main(string[] args)
{
Console.WriteLine("Before change");
ShowConfig();

Console.WriteLine("Change");
ChangeConfig();

Console.WriteLine("After change");
ShowConfig();

Console.ReadLine();
}

private static void ChangeConfig()
{

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string appConfig = File.ReadAllText(configuration.FilePath);
appConfig = appConfig.Replace("localhost:8000", "myAddress.this.com:8080");
File.WriteAllText(configuration.FilePath, appConfig);
configuration.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("endpoint");
ConfigurationManager.RefreshSection("client");
ConfigurationManager.RefreshSection("system.serviceModel");
ConfigurationManager.RefreshSection("configuration");

}

private static void ShowConfig()
{
ClientSection clientSection =
ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

ChannelEndpointElementCollection endpointCollection =
clientSection.ElementInformation.Properties[string.Empty].Value as ChannelEndpointElementCollection;

foreach (ChannelEndpointElement endpointElement in endpointCollection)
{
Console.WriteLine(endpointElement.Address);
}
}

文件确实得到了更新,因为我可以在程序运行时在文本编辑器中看到它……但是控制台显示相同的值读取了两次。我所看到的关于 RefreshSection 的大部分内容似乎暗示它更多地与 appSettings 相关,尽管我还没有看到任何直接说明这一点的内容。是否可以像我尝试的那样刷新 app.config?

最佳答案

你需要添加:

ConfigurationManager.RefreshSection("system.serviceModel/client");

您对 RefreshSection 的调用需要引用从 System.Configuration.ConfigurationSection 继承的所有内容。

关于c# - RefreshSection 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42748206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com