6

我有一个 app.config 文件,格式为:

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <system.serviceModel>
      <client>
        <endpoint address="http://something.com"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFileTransfer"
        contract="ABC" name="XXX" />
        <endpoint address="http://something2.com"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFileTransfer"
        contract="ABC2" name="YYY" />
      </client>
    </system.serviceModel>
  </configuration>

我想读取名称为“XXX”的节点端点的属性“地址”处的值。请告诉我怎么做!

(继续下面与 marc_s 的讨论。很抱歉将文本放在这里,因为评论不允许格式化代码)@marc_s:我使用下面的代码来阅读上面的文件,但它表明 clientSection.Endpoints 有 0 个成员(Count=0 )。请帮忙!

public MainWindow()
    {
        var exeFile = Environment.GetCommandLineArgs()[0];
        var configFile = String.Format("{0}.config", exeFile);
        var config = ConfigurationManager.OpenExeConfiguration(configFile);
        var wcfSection = ServiceModelSectionGroup.GetSectionGroup(config);
        var clientSection = wcfSection.Client;
        foreach (ChannelEndpointElement endpointElement in clientSection.Endpoints)
        {
            if (endpointElement.Name == "XXX")
            {
                var addr = endpointElement.Address.ToString();
            }
        }
    }
4

3 回答 3

15

您真的不需要 - WCF 运行时将为您完成所有这些工作。

如果你真的必须 - 无论出于何种原因 - 你可以这样做:

using System.Configuration;
using System.ServiceModel.Configuration;

ClientSection clientSettings = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

string address = null;

foreach(ChannelEndpointElement endpoint in clientSettings.Endpoints)
{
   if(endpoint.Name == "XXX")
   {
      address = endpoint.Address.ToString();
      break;
   }
}
于 2010-06-30T12:02:06.460 回答
3

您可以使用 ServiceModelSectionGroup (System.ServiceModel.Configuration) 来访问配置:

    var config = ConfigurationManager.GetSection("system.serviceModel") as ServiceModelSectionGroup;
    foreach (ChannelEndpointElement endpoint in config.Client.Endpoints)
    {
        Uri address = endpoint.Address;
        // Do something here
    }

希望有帮助。

于 2010-06-30T11:56:46.867 回答
0
var config = ConfigurationManager.OpenExeConfiguration("MyApp.exe.config");
var wcfSection = ServiceModelSectionGroup.GetSectionGroup(config);
var clientSection = wcfSection.Client;
foreach(ChannelEndpointElement endpointElement in clientSection.Endpoints) {
    if(endpointElement.Name == "XXX") {
        return endpointElement.Address;
    }
}
于 2010-06-30T11:55:07.650 回答