WPF程序中App.Config文件的读与写

 WPF程序中的App.Config文件是我们应用程序中经常使用的一种配置文件,System.Configuration.dll文件中提供了大量的读写的配置,所以它是一种高效的程序配置方式,那么今天我就这个部分来做一次系统性的总结。

        App.Config文件是系统默认的应用程序配置文件,在我们使用后进行编译时会生成“程序集名称+.exe.config”文件,其本质上也是一个XML文件,在我们的应用程序中添加应用程序配置文件后,默认生成下面的内容。

1
2
3
<?xml version= "1.0"  encoding= "utf-8"  ?>
<configuration>
</configuration>

  后面可以根据需要添加我们想要配置的内容,例如我们想要自定义一个section,那么我们首先需要增加一个configSections节点,然后再添加section子节点,在子节点中我们需要添加名称name 类型type等节点信息,具体配置信息如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version= "1.0"  encoding= "utf-8"  ?>
<configuration> 
  <configSections>
    <section name= "eas"  type= "EAS.ConfigHandler,EAS.MicroKernel" />
    <section name= "entityFramework"  type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"                            requirePermission= "false" />
   </configSections>
   <eas>
     <objects>
       < object   name= "MessageBus"  assembly= "EAS.MicroKernel"  type= "EAS.Sockets.Bus.SocketBus"  LifestyleType= "Singleton" >
         <property name= "Url"  type= "string"  value= "socket.tcp://127.0.0.1:1000/" />
       </ object >
     </objects>
   </eas> 
   <entityFramework>
     <defaultConnectionFactory type= "System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
     <providers>
       <provider invariantName= "MySql.Data.MySqlClient"  type= "MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" ></provider>
       <provider invariantName= "System.Data.SqlClient"  type= "System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
     </providers>
   </entityFramework>
   <startup>
       <supportedRuntime version= "v4.0"  sku= ".NETFramework,Version=v4.6" />
   </startup>
   <appSettings>   
     <add key= "AspNetAddress"  value= "http://192.168.3.199:8088" />  
     <add key= "ServerDog"  value= "192.168.3.199:8001" />
     <add key= "DICSCtrl"  value= "192.168.3.100:4503" />
     <add key= "BGServerDeamon"  value= "192.168.3.199:5915" />
     <add key= "MySQLServer"  value= "localhost" />
     <add key= "DataSimulator"  value= "DataRinse" />
     <!--当前软件部署的时间-->
     <add key= "DeploymentTime"  value= "20170822" />
     <add key= "UnitWidth"  value= "1920" />
     <!--单个屏幕高-->
     <add key= "UnitHeight"  value= "1080" />
     <!--横向屏幕数量-->
     <add key= "HorizontalCount"  value= "2" />
     <!--竖向屏幕数量-->
     <add key= "VerticalCount"  value= "2" /> 
   </appSettings>
</configuration>

  这其中最常用的就是appSettings节点了,通过添加key和value能够快速添加键值对,从而完成参数的配置与读写操作。

       第一部分:基础篇

  这一部分主要介绍最常用的操作,那就是读取操作了。 

1
string  sqlServer= System.Configuration.ConfigurationSettings.AppSettings[ "MySQLServer" ]; 

通过输入唯一的key就可以来查找当前key对应的value值的内容了。

       后面就是为App.Config文件来写入值了,我们首先来看如何为其中的某一个节点写入值的操作。

  1 将当前应用程序的配置文件作为 System.Configuration.Configuration 对象打开。

1
System.Configuration.Configuration  config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

  上面打开特定的exe.config文件的形式和下面的类似,都可以打开exe.config文件的内容,只不过下面这种方式更为灵活。

1
2
3
4
5
6
ExeConfigurationFileMap map =  new  ExeConfigurationFileMap();
Assembly assembly = Assembly.GetCallingAssembly();
Uri uri =  new  Uri(Path.GetDirectoryName(assembly.CodeBase));
map.ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name +  ".exe.config" );
System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(map, 0);
string  sqlServer = configuration.AppSettings.Settings[ "MySQLServer" ].Value;    

  2 读取和写入特定的项

1
2
3
4
5
6
//读取
string  sqlServer = config.AppSettings.Settings[ "MySQLServer" ].Value;
//写入
config.AppSettings.Settings[ "MySQLServer" ].Value =  "XXX" ;
//增加节点
  config.AppSettings.Settings.Add( "MySQLServer" , "XXX" );

  3 写入后要进行保存,并刷新

1
2
config.Save(System.Configuration.ConfigurationSaveMode.Modified);
System.Configuration.ConfigurationManager.RefreshSection( "appSettings" );

  这样我们就完成了整个读取和写入的操作了,基础的操作部分也就包含这么多的部分,通过这些操作能够对常规的一些操作进行处理,并完成软件的一些基础的要求。

  第二部分:提高篇

  这个部分我们来将一些稍微复杂一点的操作,对于appsettings中的操作,我们当然可以非常轻松的通过这些操作来完成配置,但是如果是自定义的section节点中的特定值那么我们应该怎样来进行读写操作呢?我们想其实app.config文件本质上也是一个xml文件,其实我们完全可以按照常规的xml操作的方式来进行读写操作,下面的代码以读取自定义节点中的xml文件为例来进行说明。 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
private  void  DoSaveConfig()
       {
           try
           {
               var  section = config.GetSection( "eas" );
               var  sontSection = section.CurrentConfiguration.GetSection( "objects" );
               string  filePath = section.CurrentConfiguration.FilePath;
               XmlDocument xmlDoc =  new  XmlDocument();
               xmlDoc.Load(filePath);
               #region 保存EAS部分
               XmlNode easNode = ((System.Xml.XmlElement)(xmlDoc.SelectSingleNode( "configuration/eas/objects/object/property" )));
               string  currentValue = easNode.Attributes[ "value" ].Value;
               string [] infos = currentValue.Split( new  char [] {  '/'  }, StringSplitOptions.RemoveEmptyEntries);
               if  (infos.Length == 2)
               {
                   string  info = infos[1];
                   string [] ipport = info.Split( new  char [] {  ':'  }, StringSplitOptions.RemoveEmptyEntries);
                   string  oldIp = ipport[0];
                   string  oldPort = ipport[1];
                   StringBuilder sb =  new  StringBuilder();
                   sb.Append( "socket.tcp://" ).Append(ServerIp).Append( ":" ).Append(oldPort).Append( "/" );
                   easNode.Attributes[ "value" ].Value = sb.ToString();
               }
               #endregion
 
               XmlNode appSettingsNode = xmlDoc.SelectSingleNode( "configuration/appSettings" );
               foreach  (XmlNode childNode  in  appSettingsNode.ChildNodes)
               {
                   if  (childNode.NodeType == XmlNodeType.Element)
                   {
                       switch  (childNode.Attributes[ "key" ].Value)
                       {
                           case  "AspNetAddress" :
                               StringBuilder web =  new  StringBuilder();
                               childNode.Attributes[ "value" ].Value = web.Append( "http://" ).Append(ServerIp).Append( ":" ).Append(WebPort).ToString();
                               break ;
                           case  "ServerDog" :
                               StringBuilder serverDog =  new  StringBuilder();
                               childNode.Attributes[ "value" ].Value = serverDog.Append(ServerIp).Append( ":" ).Append(ServerDogPort).ToString();
                               break ;
                           case  "DICSCtrl" :
                               StringBuilder processor =  new  StringBuilder();
                               childNode.Attributes[ "value" ].Value = processor.Append(ProcessorIp).Append( ":" ).Append(ProcessorPort).ToString();
                               break ;
                           case  "BGServerDeamon" :
                               StringBuilder bgserverdeamon =  new  StringBuilder();
                               childNode.Attributes[ "value" ].Value = bgserverdeamon.Append(ServerIp).Append( ":" ).Append(BGServerDeamonPort).ToString();
                               break ;
                           case  "MySQLServer" :
                               childNode.Attributes[ "value" ].Value = ServerIp;
                               break ;
                           case  "DeploymentTime" :
                               DeployTime = DateTime.Now.ToString( "yyyy-MM-dd" );
                               childNode.Attributes[ "value" ].Value = DeployTime;
                               break ;
                           case  "UnitWidth" :
                               childNode.Attributes[ "value" ].Value = UnitWidth.ToString();
                               break ;
                           case  "UnitHeight" :
                               childNode.Attributes[ "value" ].Value = UnitHeight.ToString();
                               break ;
                           case  "HorizontalCount" :
                               childNode.Attributes[ "value" ].Value = HCount.ToString();
                               break ;
                           case  "VerticalCount" :
                               childNode.Attributes[ "value" ].Value = VCount.ToString();
                               break ;
                           case  "CurrentVersion" :
                               childNode.Attributes[ "value" ].Value = CurrentVersion;
                               break ;
                           case  "PartialGISAddress" :
                               childNode.Attributes[ "value" ].Value = GISPath;
                               break ;
                           case  "MediaShareFolder" :
                               childNode.Attributes[ "value" ].Value = DiskMapPath;
                               break ;
                           case  "MediaSharedRemoteFolder" :
                               StringBuilder mediasharedfolder =  new  StringBuilder();
                               childNode.Attributes[ "value" ].Value = mediasharedfolder.Append( @"\\" ).Append(ServerIp).Append( @"\SharedResources" ).ToString();
                               break ;
                           case  "DynamicHTMLsPath" :
                               childNode.Attributes[ "value" ].Value = HTMLPath;
                               break ;
                           default :
                               break ;
                       }
                   }
               }
               xmlDoc.Save(filePath);
               MessageBox.Show( "配置文件参数保存成功,重启软件后生效!" "提示" , MessageBoxButtons.OK, MessageBoxIcon.Information);
           }
           catch  (Exception ex)
           {
               ;
           }
      

  这其中 config为第一部分中打开的System.Configuration.Configuration 对象,后面的部分就是一些常规的XML文件的一些操作,首先是Load然后再配置节点信息,这里配置节点的时候需要注意的是当前XmlNodeType,这个是必须要进行确认的,只有当前的XMLNodeType为Element的项才能够进行key和value的值的读写,其它的都是一些常规的操作,具体内容请参考下面的DEMO中的部分代码。

  在上面的代码中,加载xml文件到XmlDocument中除了采用xmlDoc.Load("具体路径")的方式之外,还可以采用下面的方式来进行,这里我们需要去比较两种方式的优劣。

1
2
3
string  xml = ((System.Xml.XmlElement)(System.Configuration.ConfigurationManager.GetSection( "eas" ))).InnerXml;
XmlDocument xmlDoc =  new  XmlDocument();
xmlDoc.LoadXml(xml);  

  第三部分:扩展篇

  为什么要自定义的配置节点?
  确实,有很多人在使用config文件都是直接使用appSetting的,把所有的配置参数全都塞到那里,这样做虽然不错, 但是如果参数过多,这种做法的缺点也会明显地暴露出来:appSetting中的配置参数项只能按key名来访问,不能支持复杂的层次节点也不支持强类型, 而且由于全都只使用这一个集合,你会发现:完全不相干的参数也要放在一起!

  想摆脱这种困扰吗?自定义的配置节点将是解决这个问题的一种可行方法。

  关于这方面的具体描述,请参考这里,并从当前位置下载DEMO查看具体的实例。

  最后将整个部分的测试用的DEMO放在这里,如果需要的话请点击此处进行下载。

猜你喜欢

转载自www.cnblogs.com/DreamRecorder/p/9485439.html