App.config 中读写appSettings、system.serviceModel终结点,以及自定义配置节

1.appSettings的读写

但需要配置的项很多时,将所有的配置记录到一个单独的Config.xml文件中,如: 

Config.xml文件

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
  <!--服务端 IP-->
  <add key="ServerIP" value="10.10.10.88"/>
  <!--服务端 命令端口-->
  <add key="ServerCmdPort" value="8889"/>
  <!--服务端 数据端口-->
  <add key="ServerDataPort" value="8890"/>
  <!--心跳间隔,单位:秒-->
  <add key="HeartbeatIntervalSec" value="10"/>
  <!--心跳间隔,单位:秒-->
  <add key="AutoRunDelaySec" value="10"/> 

</appSettings>

 在App.Config 引用这个配置文件: 

App.config

<?xml version="1.0" encoding="utf-8" ?>
  <appSettings file="Config.xml"></appSettings>

。。。。。下面的省略

 在项目中定义配置单例类AppSetting.cs管理配置信息: 

AppSetting.cs
  class AppSetting : BaseSingleton<AppSetting> //单例基类
    {
        #region serverIP、ServerCmdPort、ServerDataPort

        /// <summary>
        /// Socket服务端IP
        /// </summary>
        public string ServerIP;
        /// <summary>
        /// AgentServer Command Port
        /// </summary>
        public int ServerCmdPort;
        /// <summary>
        /// AgentServer Data Port
        /// </summary>
        public int ServerDataPort;

        /// <summary>
        ///保存配置信息
        /// </summary>
        public void SaveServerConfig()
        {
            this.SetConfigValue("ServerIP", this.ServerIP);
            this.SetConfigValue("ServerCmdPort", this.ServerCmdPort.ToString());
            this.SetConfigValue("ServerDataPort", this.ServerDataPort.ToString());
        }
        #endregion   
     
        public AppSetting()
        {
            this.ServerIP = this.GetConfigValue<string>("ServerIP", "127.0.0.1");
            this.ServerCmdPort = this.GetConfigValue<int>("ServerCmdPort", 8889);
            this.ServerDataPort = this.GetConfigValue<int>("ServerDataPort", 8890);
            this.HeartbeatIntervalSec = this.GetConfigValue<int>("HeartbeatIntervalSec", 60); 
        }


        private T GetConfigValue<T>(string hashKey, T defaultValue)
        {
            try
            {
                return (T)Convert.ChangeType(ConfigurationManager.AppSettings[hashKey], typeof(T));

            }
            catch (Exception)
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 修改AppSettings中配置项的内容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void SetConfigValue(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
                config.AppSettings.Settings[key].Value = value;
            else
                config.AppSettings.Settings.Add(key, value);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }

读写配置信息:

读写

  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的Address

App.config     <services>
      <service behaviorConfiguration="managerBehavior" name="SMYH.WinFormService.WCF.GSMService">
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <endpoint name="GSMServer" address="net.tcp://localhost:2011/GSMServer/" binding="netTcpBinding" bindingConfiguration="netTcpBinding_Service" contract="SMYH.WinFormService.WCF.IGSMService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9999/GSMServer/" />
          </baseAddresses>
        </host>
      </service>
    </services>

读取和修改 address值(做为服务一般不用修改这个路径),代码:

读取、设置Address
     /// <summary>
        /// 读取EndpointAddress
        /// </summary>
        /// <param name="endpointName"></param>
        /// <returns></returns>
        private string GetEndpointAddress(string endpointName)
        {
            ServicesSection servicesSection = config.GetSection("system.serviceModel/services") as ServicesSection;
            foreach (ServiceElement service in servicesSection.Services)
            {
                foreach (ServiceEndpointElement item in service.Endpoints)
                {
                    if (item.Name == endpointName)
                        return item.Address.ToString();
                }
            }
            return string.Empty;
        }


        /// <summary>
        /// 设置EndpointAddress
        /// </summary>
        /// <param name="endpointName"></param>
        /// <param name="address"></param>
        private void SetEndpointAddress(string endpointName, string address)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServicesSection clientSection = config.GetSection("system.serviceModel/services") as ServicesSection;
            foreach (ServiceElement service in clientSection.Services)
            {
                foreach (ServiceEndpointElement item in service.Endpoints)
                {
                    if (item.Name == endpointName)
                    {
                        item.Address = new Uri(address);
                        break;
                    }                       
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }

修改Wcf客户端Client的Endpoint

WcfClient配置    <client>
      <endpoint address="net.tcp://localhost:2011/GSMServer/" binding="netTcpBinding"
              bindingConfiguration="GSMServer" contract="GsmServiceReference.IGSMService"
              name="GSMServer" />
    </client>  

 

读取和修改 address值:

/// <summary>
        /// 读取EndpointAddress
        /// </summary>
        /// <param name="endpointName"></param>
        /// <returns></returns>
        private string GetEndpointAddress(string endpointName)
        {
            ClientSection clientSection = config.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 name="endpointName"></param>
        /// <param name="address"></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的代码:

CreateClient
    /// <summary>
        /// 建立到数据服务的客户端,主要是更换配置文件中指定的数据服务IP地址
        /// </summary>
        /// <returns></returns>
        private GSMServiceClient CreateClient(string serverIP)
        {
            try
            {
                InstanceContext context = new InstanceContext(Callback);
                GSMServiceClient client = new GSMServiceClient(context);
                string uri = client.Endpoint.Address.Uri.AbsoluteUri;
                uri = uri.Replace("localhost", serverIP);//更换数据服务IP地址
                EndpointAddress temp = client.Endpoint.Address;
                client.Endpoint.Address = new EndpointAddress(new Uri(uri), temp.Identity, temp.Headers);
                client.InnerChannel.Faulted += new EventHandler(InnerChannel_Faulted);
                return client;
            }
            catch (Exception)
            {
                throw;
            }
        }

 3.自定义配置节的使用

   直接使用江大鱼的SuperSocket里的配置类,SuperSocket很好用,通过看江大的代码学到了好多,再此谢过。

 先看看配置文件:

<configuration>
  <configSections>
    <section name="socketServer" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
  </configSections>
  <appSettings file="Config.xml"></appSettings>
  <socketServer>
    <servers>
      <server name="F101ApiCmdServer"
           serviceName="F101ApiCmdService" ip="Any" port="8889" mode="Async">
      </server>
      <server name="F101ApiDataServer"
               serviceName="F101ApiDataService" ip="Any" port="8890" mode="Async">
      </server>
    </servers>
    <services>
      <service name="F101ApiCmdService"
              type="SMYH.API.Server.F101.F101ApiCmdServer,ApiServer" />
      <service name="F101ApiDataService"
             type="SMYH.API.Server.F101.F101ApiDataServer,ApiServer" />
    </services>
    <connectionFilters>
    </connectionFilters>
  </socketServer>
</configuration>

 自定义扩展的配置节类SocketServiceConfig

 1   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         IEnumerable<IServerConfig> IConfig.Servers
 87         {
 88             get
 89             {
 90                 return this.Servers;
 91             }
 92         }
 93 
 94         IEnumerable<IServiceConfig> IConfig.Services
 95         {
 96             get
 97             {
 98                 return this.Services;
 99             }
100         }
101         
102         IEnumerable<IConnectionFilterConfig> 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         }

最后记录一个设置开机自启动的代码

 1         /// <summary> 
 2         /// 开机启动项 
 3         /// </summary> 
 4         /// <param name=\"Started\">是否启动</param> 
 5         /// <param name=\"name\">启动值的名称</param> 
 6         /// <param name=\"path\">启动程序的路径</param> 
 7         private void RunWhenStart(bool Started, string name, string path)
 8         {
 9             RegistryKey HKLM = Registry.LocalMachine;
10             RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");
11             if (Started == true)
12             {
13                 try
14                 {
15                     Run.SetValue(name, path);
16                     HKLM.Close();
17                 }
18                 catch (Exception)
19                 {
20                 }
21             }
22             else
23             {
24                 try
25                 {
26                     Run.DeleteValue(name);
27                     HKLM.Close();
28                 }
29                 catch (Exception)
30                 {
31 
32                 }
33             }
34         }

调用代码:

        this.RunWhenStart(this.IsAutoStart, this.SoftName, Application.ExecutablePath);

希望这些代码能对别人有点作用。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值