.exe.config文件中serviceModel/client/endpoint的读取和修改

最近自己写的一个小项目中,遇到了需要给客户提供配置界面的需求,原来运行WCF服务的软件,都是在web.config中进行配置,客户都是小白,基本不会,而且牵涉到升级软件,需要更新config文件的问题。因此,决定加入一个config配置读取和写入的功能。
读取配置:


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

Configuration exeConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var serviceModel = ServiceModelSectionGroup.GetSectionGroup(exeConfig);
ChannelEndpointElement ep = null;
string Svc1Url = null; string Svc2Url = null;
for (int i = serviceModel.Client.Endpoints.Count - 1; i >= 0; i--)
{
	ep = serviceModel.Client.Endpoints[i];
	if (ep.Name == "svc1")  // 修改为自己的 svcname
	{
		Svc1Url = ep.Address.ToString();                    
	}
	else if (ep.Name == "svc2")
	{
		Svc2Url = ep.Address.ToString();
	}
}

保存配置:

Configuration exeConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var serviceModel = ServiceModelSectionGroup.GetSectionGroup(exeConfig);
ChannelEndpointElement epSvc1 = null, epSvc2 = null;
for(int i = serviceModel.Client.Endpoints.Count - 1; i >= 0; i--)
{
	ChannelEndpointElement ep = serviceModel.Client.Endpoints[i];
	if (ep.Name == "svc1")
	{
		// 保存到配置文件,尝试先删除,再添加。
		epSvc1 = ep;
		serviceModel.Client.Endpoints.Remove(epSvc1);
	}
	else if (ep.Name == "svc2")
	{
		epSvc2 = ep;
		serviceModel.Client.Endpoints.Remove(epSvc2);
	}
}
if (epSvc1 == null || epSvc2 == null)
{
	MessageBox.Show("未能在默认配置文件中找到服务地址的配置项,请重新安装本服务,确保 .config 文件的配置完整。");
	return;
}
epSvc1 = new ChannelEndpointElement(new System.ServiceModel.EndpointAddress("http://localhost/Svc1), epSvc1.Contract)
{
	Binding = epSvc1.Binding,
	Name = epSvc1.Name,
	BindingConfiguration = epSvc1.BindingConfiguration
};
serviceModel.Client.Endpoints.Add(epSvc1);
epSvc2 = new ChannelEndpointElement(new System.ServiceModel.EndpointAddress("http://localhost/Svc2.svc")), epSvc2.Contract)
{
	Binding = epSvc2.Binding,
	Name = epSvc2.Name,
	BindingConfiguration = epSvc2.Binding
};
serviceModel.Client.Endpoints.Add(epSvc2);
serviceModel.Client.SectionInformation.ForceSave = true;
// 不删除节点,再加入,保存就会失败
exeConfig.Save();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值