Cómo leer el valor de un atributo definido en app.config?
-
01-10-2019 - |
Pregunta
Tengo un archivo app.config que en la forma de:
<?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>
Quiero leer el valor al atributo "dirección" de punto final nodo que tiene el nombre = "XXX". Por favor, muéstrame cómo hacerlo!
(Continuar belowing disscussing con marc_s. En este momento de poner el texto aquí desde comentario no permiten a los códigos de formato) @marc_s: Yo uso el siguiente código para leer el archivo anterior pero muestra que los clientSection.Endpoints tiene 0 miembros (Count = 0). Por favor, ayuda!
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();
}
}
}
Solución
Realmente no es necesario -. El tiempo de ejecución de WCF va a hacer todo esto para usted
Si realmente tiene que - por cualquier razón - usted puede hacer esto:
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;
}
}
Otros consejos
Puede utilizar el ServiceModelSectionGroup (System.ServiceModel.Configuration) para acceder a la configuración:
var config = ConfigurationManager.GetSection("system.serviceModel") as ServiceModelSectionGroup;
foreach (ChannelEndpointElement endpoint in config.Client.Endpoints)
{
Uri address = endpoint.Address;
// Do something here
}
Espero que ayude.
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;
}
}