最近自己写的一个小项目中,遇到了需要给客户提供配置界面的需求,原来运行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();