DotNet 笔记

东方欲晓,莫道君起早。

.NET操作符合ini文件规则的配置文件组件SharpConfig

        本文章主要介绍使用第三方类库SharpConfig如何操作使用INI文件

        dll下载:SharpConfig.dll (34.50 kb)

        配置文件有很多如INI配置文件,XML配置文件,还有就是可以使用系统注册表等。在早期的windows桌面系统中主要是用INI文件作为系统的配置文件,从win95以后开始转向使用注册表,但是还有很多系统配置是使用INI文件的。其实INI文件就是简单的text文件,只不过这种txt文件要遵循一定的INI文件格式。当然INI file的后缀名也不一定是".ini"也可以是".cfg"或者是".txt"。

1:INI文件由节、键、值组成。  

节 
[section]  

参数(键=值) 
name=value

注解 
注解使用#表示,经典ini文件使用分号(;)表示。在分号后面的文字,直到该行结尾都全部为注解。

 形如:

#Declare a section called "General".
# All settings that are below the section belong to it,
# until another section is declared.
[General]
SomeInteger = 10
SomeFloat = 20.05

# An array is identified by the brackets surrounding the value.
AnArray = {0,2,5,7}

# Another section called "Video".
[Video]
Width = 1920 # this is an inline comment.
Height = 1200 # inline comments are parsed by SharpConfig.
Format = RGB24

# Another section.
[OtherProperties]

# A boolean can be represented by one of the following values:
# true:   yes, 1, true, on
# false:  no, 0, false, off
ABoolean = yes
ABooleanArray = {on,off,yes,no,true,false}

AnEmptyArray = {}
AnotherEmptyArray = {      }

2.Net如何方便的操作这种文件?

使用SharpConfig,改DLL是.NET平台一个使用非常简单的处理Cfg/ini配置文件的类库。

项目主页:https://github.com/cemdervis/SharpConfig,目前最新版本是1.4.3;

Nuget包主页:https://www.nuget.org/packages/sharpconfig/,其主要功能有:

a.支持的配置文件类型有cfg,ini格式;

b.支持注释功能,使用 # 符号开头;

c.支持直接读取和写入指定节点的值;

d.支持枚举,数组,以及和实体的直接映射;

e.支持内存的创建和使用,相对一个配置类型,直接在代码中初始化和使用;

3:示例代码:

using SharpConfig;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SharpConfigDo
{
    class Program
    {
        static void Main(string[] args)
        {
            //载入已有的Config文件
            HowToLoadAConfig();

            //创建一个config文件文档内容(并没有保存为文件)
            // HowToCreateAConfig();

            //保存文档
            //HowToSaveAConfig(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TestCfg.ini"));

            //把配置文件节点序列化为对象
            //HowToCreateObjectsFromSections();

            //把对象序列化为Config文件的节点
            //HowToCreateSectionsFromObjects();

            //如何操作数组
            //HowToHandleArrays();

            Console.ReadLine();
        }

        /// <summary>
        /// Shows how to load a configuration from a string (our sample config).
        /// The same works for loading files and streams. Just call the appropriate method
        /// such as LoadFromFile and LoadFromStream, respectively.
        /// </summary>
        static void HowToLoadAConfig()
        {
            // Read our example config.
            //var cfg = Configuration.LoadFromString(Properties.Resources.SampleCfg);
            var cfg = Configuration.LoadFromFile(@"Config/SampleCfg.txt");
            // Just print all sections and their settings.
            PrintConfig(cfg);
        }

        /// <summary>
        /// Shows how to create a configuration in memory.
        /// </summary>
        static void HowToCreateAConfig()
        {
            Configuration cfg = new Configuration();

            cfg["SomeStructure"]["SomeString"].StringValue = "foobar";
            cfg["SomeStructure"]["SomeInt"].IntValue = 2000;
            cfg["SomeStructure"]["SomeInts"].IntValueArray = new[] { 1, 2, 3 };
            cfg["SomeStructure"]["SomeDate"].DateTimeValue = DateTime.Now;

            // We can obtain the values directly as strings, ints, floats, or any other (custom) type,
            // as long as the string value of the setting can be converted to the type you wish to obtain.
            string nameValue = cfg["SomeStructure"]["SomeString"].StringValue;
            int ageValue = cfg["SomeStructure"]["SomeInt"].IntValue;
            DateTime dateValue = cfg["SomeStructure"]["SomeDate"].DateTimeValue;

            // Print our config just to see that it works.
            PrintConfig(cfg);
        }

        /// <summary>
        /// Shows how to save a configuration to a file.
        /// </summary>
        /// <param name="filename">The destination filename.</param>
        static void HowToSaveAConfig(string filename)
        {
            var cfg = new Configuration();

            cfg["SomeStructure"]["SomeString"].StringValue = "foobar";
            cfg["SomeStructure"]["SomeInt"].IntValue = 2000;
            cfg["SomeStructure"]["SomeInts"].IntValueArray = new[] { 1, 2, 3 };
            cfg["SomeStructure"]["SomeDate"].DateTimeValue = DateTime.Now;

            cfg.SaveToFile(filename);

            Console.WriteLine("The config has been saved to {0}!", filename);
        }

        /// <summary>
        /// Shows how to create C#/.NET objects directly from sections.
        /// </summary>
        static void HowToCreateObjectsFromSections()
        {
            var cfg = new Configuration();

            // Create the section.
            cfg["SomeStructure"]["SomeString"].StringValue = "foobar";
            cfg["SomeStructure"]["SomeInt"].IntValue = 2000;
            cfg["SomeStructure"]["SomeInts"].IntValueArray = new[] { 1, 2, 3 };
            cfg["SomeStructure"]["SomeDate"].DateTimeValue = DateTime.Now;

            // Now create an object from it.
            var p = cfg["SomeStructure"].ToObject<SomeClass>();

            // Test.
            Console.WriteLine("SomeString:   " + p.SomeString);
            Console.WriteLine("SomeInt:      " + p.SomeInt);
            PrintArray("SomeInts", p.SomeInts);
            Console.WriteLine("SomeDate:     " + p.SomeDate);
        }

        /// <summary>
        /// Shows how to create sections directly from C#/.NET objects.
        /// </summary>
        static void HowToCreateSectionsFromObjects()
        {
            var cfg = new Configuration();

            // Create an object.
            var p = new SomeClass();
            p.SomeString = "foobar";
            p.SomeInt = 2000;
            p.SomeInts = new[] { 1, 2, 3 };
            p.SomeDate = DateTime.Now;

            // Now create a section from it.
            cfg.Add(Section.FromObject("SomeStructure", p));

            // Print the config to see that it worked.
            PrintConfig(cfg);
        }

        /// <summary>
        /// Shows the usage of arrays in SharpConfig.
        /// </summary>
        static void HowToHandleArrays()
        {
            var cfg = new Configuration();

            cfg["GeneralSection"]["SomeInts"].IntValueArray = new[] { 1, 2, 3 };

            // Get the array back.
            int[] someIntValuesBack = cfg["GeneralSection"]["SomeInts"].GetValueArray<int>();
            float[] sameValuesButFloats = cfg["GeneralSection"]["SomeInts"].GetValueArray<float>();
            string[] sameValuesButStrings = cfg["GeneralSection"]["SomeInts"].GetValueArray<string>();

            // There is also a non-generic variant of GetValueArray:
            object[] sameValuesButObjects = cfg["GeneralSection"]["SomeInts"].GetValueArray(typeof(int));

            PrintArray("someIntValuesBack", someIntValuesBack);
            PrintArray("sameValuesButFloats", sameValuesButFloats);
            PrintArray("sameValuesButStrings", sameValuesButStrings);
            PrintArray("sameValuesButObjects", sameValuesButObjects);
        }

        /// <summary>
        /// Prints all sections and their settings to the console.
        /// </summary>
        /// <param name="cfg">The configuration to print.</param>
        static void PrintConfig(Configuration cfg)
        {
            foreach (Section section in cfg)
            {
                Console.WriteLine("[{0}]", section.Name);

                foreach (Setting setting in section)
                {
                    Console.Write("  ");

                    if (setting.IsArray)
                        Console.Write("[Array, {0} elements] ", setting.ArraySize);

                    Console.WriteLine(setting.ToString());
                }
                Console.WriteLine();
            }
        }

        // Small helper method.
        static void PrintArray<T>(string arrName, T[] arr)
        {
            Console.Write(arrName + " = { ");

            for (int i = 0; i < arr.Length - 1; i++)
                Console.Write(arr[i].ToString() + ", ");

            Console.Write(arr[arr.Length - 1].ToString());
            Console.WriteLine(" }");
        }
    }

    #region 用于序列化的模拟类SomeClass
    class SomeClass
    {
        public string SomeString { get; set; }
        public int SomeInt { get; set; }
        public int[] SomeInts { get; set; }
        public DateTime SomeDate { get; set; }

        // This field will be ignored by SharpConfig
        // when creating sections from objects and vice versa.
        [SharpConfig.Ignore]
        public int SomeIgnoredField = 0;

        // Same for this property.
        [SharpConfig.Ignore]
        public int SomeIgnoredProperty { get; set; }
    }
    #endregion
}

SharpConfig.dll (34.50 kb)

 

 

Loading