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
 1   class AppSetting : BaseSingleton<AppSetting> //单例基类
 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.GetConfigValue<string>("ServerIP""127.0.0.1");
32             this.ServerCmdPort = this.GetConfigValue<int>("ServerCmdPort"8889);
33             this.ServerDataPort = this.GetConfigValue<int>("ServerDataPort"8890);
34             this.HeartbeatIntervalSec = this.GetConfigValue<int>("HeartbeatIntervalSec"60); 
35         }
36 
37 
38         private T GetConfigValue<T>(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 name="key"></param>
55         /// <param name="value"></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的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>

好像默认生成的没有name属性,我记不清了,如果没有就自己加上。

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

读取、设置Address
 1      /// <summary>
 2         /// 读取EndpointAddress
 3         /// </summary>
 4         /// <param name="endpointName"></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 name="endpointName"></param>
25         /// <param name="address"></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的Endpoint

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

读取和修改 address值:

 

View Code
        /// <summary>
        
/// 读取EndpointAddress
        
/// </summary>
        
/// <param name="endpointName"></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 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
 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 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

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         }

 

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

 

RunWhenStart
 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);

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

原文地址:https://www.cnblogs.com/zhaobl/p/appsettingHelper.html