App.config 中读写appSettings、system.serviceModel终结点,以及自定义配置节 项目总结1.appSettings的读写但需要配置的项很多时将所有的配置记录到一个单独的Config.xml文件中如Config.xml文件 ?xml version1.0 encodingutf-8 ? appSettings !--服务端 IP-- add keyServerIP value10.10.10.88/ !--服务端 命令端口-- add keyServerCmdPort value8889/ !--服务端 数据端口-- add keyServerDataPort value8890/ !--心跳间隔,单位:秒-- add keyHeartbeatIntervalSec value10/ !--心跳间隔,单位:秒-- add keyAutoRunDelaySec value10/ /appSettings在App.Config 引用这个配置文件App.config ?xml version1.0 encodingutf-8 ? appSettings fileConfig.xml/appSettings 。。。。。下面的省略在项目中定义配置单例类AppSetting.cs管理配置信息1 class AppSetting : BaseSingletonAppSetting //单例基类 2 { 3 #region serverIP、ServerCmdPort、ServerDataPort 4 5 /// summary 6 /// Socket服务端IP 7 /// /summary 8 public string ServerIP; 9 /// summary 10 /// AgentServer Command Port 11 /// /summary 12 public int ServerCmdPort; 13 /// summary 14 /// AgentServer Data Port 15 /// /summary 16 public int ServerDataPort; 17 18 /// summary 19 ///保存配置信息 20 /// /summary 21 public void SaveServerConfig() 22 { 23 this.SetConfigValue(ServerIP, this.ServerIP); 24 this.SetConfigValue(ServerCmdPort, this.ServerCmdPort.ToString()); 25 this.SetConfigValue(ServerDataPort, this.ServerDataPort.ToString()); 26 } 27 #endregion 28 29 public AppSetting() 30 { 31 this.ServerIP this.GetConfigValuestring(ServerIP, 127.0.0.1); 32 this.ServerCmdPort this.GetConfigValueint(ServerCmdPort, 8889); 33 this.ServerDataPort this.GetConfigValueint(ServerDataPort, 8890); 34 this.HeartbeatIntervalSec this.GetConfigValueint(HeartbeatIntervalSec, 60); 35 } 36 37 38 private T GetConfigValueT(string hashKey, T defaultValue) 39 { 40 try 41 { 42 return (T)Convert.ChangeType(ConfigurationManager.AppSettings[hashKey], typeof(T)); 43 44 } 45 catch (Exception) 46 { 47 return defaultValue; 48 } 49 } 50 51 /// summary 52 /// 修改AppSettings中配置项的内容 53 /// /summary 54 /// param namekey/param 55 /// param namevalue/param 56 public void SetConfigValue(string key, string value) 57 { 58 Configuration config ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 59 if (config.AppSettings.Settings[key] ! null) 60 config.AppSettings.Settings[key].Value value; 61 else 62 config.AppSettings.Settings.Add(key, value); 63 config.Save(ConfigurationSaveMode.Modified); 64 ConfigurationManager.RefreshSection(appSettings); 65 } 66 }读写配置信息读写 this.textBox_服务器地址.Text AppSetting.Instance.ServerIP; this.textBox_服务命令端口.Text AppSetting.Instance.ServerCmdPort.ToString(); this.textBox_服务数据端口.Text AppSetting.Instance.ServerDataPort.ToString(); AppSetting.Instance.ServerIP this.textBox_服务器地址.Text; AppSetting.Instance.ServerCmdPort int.Parse(this.textBox_服务命令端口.Text); AppSetting.Instance.ServerDataPort int.Parse(this.textBox_服务数据端口.Text); AppSetting.Instance.SaveServerConfig();2.system.serviceModel终结点的读写修改Wcf服务端Service的Addressservices service behaviorConfigurationmanagerBehavior nameSMYH.WinFormService.WCF.GSMService endpoint addressmex bindingmexHttpBinding contractIMetadataExchange / endpoint nameGSMServer addressnet.tcp://localhost:2011/GSMServer/ bindingnetTcpBinding bindingConfigurationnetTcpBinding_Service contractSMYH.WinFormService.WCF.IGSMService / host baseAddresses add baseAddresshttp://localhost:9999/GSMServer/ / /baseAddresses /host /service /services好像默认生成的没有name属性我记不清了如果没有就自己加上。读取和修改 address值(做为服务一般不用修改这个路径)代码/// summary 2 /// 读取EndpointAddress 3 /// /summary 4 /// param nameendpointName/param 5 /// returns/returns 6 private string GetEndpointAddress(string endpointName) 7 { 8 ServicesSection servicesSection ConfigurationManager.GetSection(system.serviceModel/services) as ServicesSection; 9 foreach (ServiceElement service in servicesSection.Services) 10 { 11 foreach (ServiceEndpointElement item in service.Endpoints) 12 { 13 if (item.Name endpointName) 14 return item.Address.ToString(); 15 } 16 } 17 return string.Empty; 18 } 19 20 21 /// summary 22 /// 设置EndpointAddress 23 /// /summary 24 /// param nameendpointName/param 25 /// param nameaddress/param 26 private void SetEndpointAddress(string endpointName, string address) 27 { 28 Configuration config ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 29 ServicesSection clientSection config.GetSection(system.serviceModel/services) as ServicesSection; 30 foreach (ServiceElement service in clientSection.Services) 31 { 32 foreach (ServiceEndpointElement item in service.Endpoints) 33 { 34 if (item.Name endpointName) 35 { 36 item.Address new Uri(address); 37 break; 38 } 39 } 40 } 41 config.Save(ConfigurationSaveMode.Modified); 42 ConfigurationManager.RefreshSection(system.serviceModel); 43 }修改Wcf客户端Client的Endpointclient endpoint addressnet.tcp://localhost:2011/GSMServer/ bindingnetTcpBinding bindingConfigurationGSMServer contractGsmServiceReference.IGSMService nameGSMServer / /client读取和修改 address值/// summary /// 读取EndpointAddress /// /summary /// param nameendpointName/param /// returns/returns private string GetEndpointAddress(string endpointName) { ClientSection clientSection ConfigurationManager.GetSection(system.serviceModel/client) as ClientSection; foreach (ChannelEndpointElement item in clientSection.Endpoints) { if (item.Name endpointName) return item.Address.ToString(); } return string.Empty; } /// summary /// 设置EndpointAddress /// /summary /// param nameendpointName/param /// param nameaddress/param private void SetEndpointAddress(string endpointName, string address) { Configuration config ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ClientSection clientSection config.GetSection(system.serviceModel/client) as ClientSection; foreach (ChannelEndpointElement item in clientSection.Endpoints) { if (item.Name ! endpointName) continue; item.Address new Uri(address); break; } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(system.serviceModel); }一般项目中只是修改address中的localhost为服务器IP即可贴一段修改IP的代码1 /// summary 2 /// 建立到数据服务的客户端,主要是更换配置文件中指定的数据服务IP地址 3 /// /summary 4 /// returns/returns 5 private GSMServiceClient CreateClient(string serverIP) 6 { 7 try 8 { 9 InstanceContext context new InstanceContext(Callback); 10 GSMServiceClient client new GSMServiceClient(context); 11 string uri client.Endpoint.Address.Uri.AbsoluteUri; 12 uri uri.Replace(localhost, serverIP);//更换数据服务IP地址 13 EndpointAddress temp client.Endpoint.Address; 14 client.Endpoint.Address new EndpointAddress(new Uri(uri), temp.Identity, temp.Headers); 15 client.InnerChannel.Faulted new EventHandler(InnerChannel_Faulted); 16 return client; 17 } 18 catch (Exception) 19 { 20 throw; 21 } 22 }3.自定义配置节的使用直接使用江大鱼的SuperSocket里的配置类SuperSocket很好用通过看江大的代码学到了好多再此谢过。先看看配置文件configuration configSections section namesocketServer typeSuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine/ /configSections appSettings fileConfig.xml/appSettings socketServer servers server nameF101ApiCmdServer serviceNameF101ApiCmdService ipAny port8889 modeAsync /server server nameF101ApiDataServer serviceNameF101ApiDataService ipAny port8890 modeAsync /server /servers services service nameF101ApiCmdService typeSMYH.API.Server.F101.F101ApiCmdServer,ApiServer / service nameF101ApiDataService typeSMYH.API.Server.F101.F101ApiDataServer,ApiServer / /services connectionFilters /connectionFilters /socketServer /configuration自定义扩展的配置节类SocketServiceConfig1 public class SocketServiceConfig : ConfigurationSection, IConfig 2 { 3 [ConfigurationProperty(servers)] 4 public ServerCollection Servers 5 { 6 get 7 { 8 return this[servers] as ServerCollection; 9 } 10 } 11 12 [ConfigurationProperty(services)] 13 public ServiceCollection Services 14 { 15 get 16 { 17 return this[services] as ServiceCollection; 18 } 19 } 20 21 [ConfigurationProperty(connectionFilters, IsRequired false)] 22 public ConnectionFilterConfigCollection ConnectionFilters 23 { 24 get 25 { 26 return this[connectionFilters] as ConnectionFilterConfigCollection; 27 } 28 } 29 30 [ConfigurationProperty(credential, IsRequired false)] 31 public CredentialConfig Credential 32 { 33 get 34 { 35 return this[credential] as CredentialConfig; 36 } 37 } 38 39 [ConfigurationProperty(loggingMode, IsRequired false, DefaultValue ShareFile)] 40 public LoggingMode LoggingMode 41 { 42 get 43 { 44 return (LoggingMode)this[loggingMode]; 45 } 46 } 47 48 [ConfigurationProperty(maxWorkingThreads, IsRequired false, DefaultValue -1)] 49 public int MaxWorkingThreads 50 { 51 get 52 { 53 return (int)this[maxWorkingThreads]; 54 } 55 } 56 57 [ConfigurationProperty(minWorkingThreads, IsRequired false, DefaultValue -1)] 58 public int MinWorkingThreads 59 { 60 get 61 { 62 return (int)this[minWorkingThreads]; 63 } 64 } 65 66 [ConfigurationProperty(maxCompletionPortThreads, IsRequired false, DefaultValue -1)] 67 public int MaxCompletionPortThreads 68 { 69 get 70 { 71 return (int)this[maxCompletionPortThreads]; 72 } 73 } 74 75 [ConfigurationProperty(minCompletionPortThreads, IsRequired false, DefaultValue -1)] 76 public int MinCompletionPortThreads 77 { 78 get 79 { 80 return (int)this[minCompletionPortThreads]; 81 } 82 } 83 84 #region IConfig implementation 85 86 IEnumerableIServerConfig IConfig.Servers 87 { 88 get 89 { 90 return this.Servers; 91 } 92 } 93 94 IEnumerableIServiceConfig IConfig.Services 95 { 96 get 97 { 98 return this.Services; 99 } 100 } 101 102 IEnumerableIConnectionFilterConfig IConfig.ConnectionFilters 103 { 104 get 105 { 106 return this.ConnectionFilters; 107 } 108 } 109 110 ICredentialConfig IRootConfig.CredentialConfig 111 { 112 get { return this.Credential; } 113 } 114 115 #endregion 116 }。。。。。省略若干类,详细看SuperSocket的源码部分吧。读写自定义配置节1 private string GetSSServiceConfigValue(string serverName, string defaultValue) 2 { 3 4 SocketServiceConfig serverConfig ConfigurationManager.GetSection(socketServer) as SocketServiceConfig; 5 if (serverConfig null) 6 return defaultValue; 7 8 foreach (SuperSocket.SocketEngine.Configuration.Server server in serverConfig.Servers) 9 { 10 if (server.Name serverName) 11 { 12 return string.Format({0}:{1}, server.Ip, server.Port.ToString()); 13 } 14 } 15 return defaultValue; 16 } 17 18 private void SetSSServiceConfigValue(string serverName, string ipPort) 19 { 20 if (!ipPort.Contains(:)) 21 return; 22 string ip ipPort.Substring(0, ipPort.IndexOf(:)); 23 int port int.Parse(ipPort.Substring(ipPort.IndexOf(:) 1)); 24 25 Configuration config ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 26 SocketServiceConfig serverConfig config.GetSection(socketServer) as SocketServiceConfig; 27 if (serverConfig null) 28 return; 29 30 foreach (SuperSocket.SocketEngine.Configuration.Server server in serverConfig.Servers) 31 { 32 if (server.Name serverName) 33 { 34 server.Ip ip; 35 server.Port port; 36 } 37 } 38 config.Save(ConfigurationSaveMode.Modified); 39 ConfigurationManager.RefreshSection(socketServer); 40 }