c# SharpConfig(读取)

Configuration在解析过程中,每碰到一个Section,就添加到列表中。而Section的区分就是靠Name,所以,我们在配置文件中注意不要把Section的名称搞混淆了。

[line1]  #线号——注释
name=长边线
Row1=30
Column1=10
Row2=100
Column2=120
distance=10
length1=40
length2=20
sigma=1
threshold=30
transition=negative
select=first

 

每一个Section下面可以有多个Setting设置。下面看看Setting类的情况。 Setting主要是获取和设置值的方法,如代码:        
     

  private void read_cfg()
        {
            Configuration config = Configuration.LoadFromFile(@"C:\measure\cam1\config.cfg", Encoding.GetEncoding("gb2312"));
            Section section = config["line1"];

            string name = section["name"].GetValue<string>();
            string select = section["select"].GetValue<string>();
            double Row1 = section["Row1"].GetValue<double>();
            double Column1 = section["Column1"].GetValue<double>();
            double Row2 = section["Row2"].GetValue<double>();
            double Column2 = section["Column2"].GetValue<double>();
            int distance = section["distance"].GetValue<int>();
           
        }

 

修改配置值需要保存的时候,也一定要加上编码,否则会导致其他的配置都发生乱码的情况。如下面的代码:

config.Save("config.cfg", Encoding.GetEncoding("gb2312"));

 

 

 

 

Section源码中没有特别需要注意的地方,主要是这里检测和移除节点的方法,如下面代码:

 1 /// <summary>检测节中是否存在某个特定名称的设置 </summary>
 2 /// <param name="settingName">设置项的名称</param>
 3 /// <returns>True if the setting is contained in the section; false otherwise.</returns>
 4 public bool Contains(string settingName)
 5 {
 6     return GetSetting(settingName) != null;
 7 }
 8 
 9 /// <summary>从本节中移除某个名称的设置</summary>
10 public void Remove(string settingName)
11 {
12     if (string.IsNullOrEmpty(settingName))
13         throw new ArgumentNullException("settingName");
14 
15     var setting = GetSetting(settingName);
16 
17     if (setting == null)
18     {
19         throw new ArgumentException("The specified setting does not exist in the section.");
20     }
21     mSettings.Remove(setting);
22 }

 




 
来源: https://yq.aliyun.com/articles/341270?spm=a2c4e.11153940.0.0.297176a8qqnuWA

 

posted @ 2019-08-19 17:33  xf_ls  阅读(846)  评论(0)    收藏  举报