Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read value of an attribute defined in app.config?

I have a app.config file that in the form of :

<?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>

I want to read the value at attribute "address" of node endpoint which has the name="XXX". Please show me how to do it!

(Continue belowing disscussing with marc_s. Sorry to put the text here since comment do not allow to format codes ) @marc_s: I use the below codes to read the above file but it shows that the clientSection.Endpoints has 0 members (Count=0). Please help!

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();
            }
        }
    }
like image 348
Nam G VU Avatar asked Jun 30 '10 11:06

Nam G VU


2 Answers

You really don't need to - the WCF runtime will do all of that for you.

If you really must - for whatever reason - you can do this:

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;
   }
}
like image 144
marc_s Avatar answered Nov 01 '22 16:11

marc_s


You can use the ServiceModelSectionGroup (System.ServiceModel.Configuration) to access the configuration:

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

Hope that helps.

like image 29
Matthew Abbott Avatar answered Nov 01 '22 16:11

Matthew Abbott