代码编织梦想


前言

在计算机科学领域,配置文件(英语:configuration file,台湾作设定档)是一种计算机文件,可以为一些计算机程序配置参数和初始设置。

SharpConfig是一个易于使用的CFG/INI配置库,用于.NET。可以使用 SharpConfig 以文本或二进制格式读取、修改和保存配置文件和流。该库与.NET,.NET Core和Mono Framework完全兼容。

SharpConfig官网:https://github.com/dlemstra/Magick.NET

在这里插入图片描述

一、SharpConfig的使用

1.安装包

SharpConfig

在这里插入图片描述

2.创建配置文件

[General]
# a comment
SomeString = Hello World!
SomeInteger = 10 # an inline comment
SomeFloat = 20.05
SomeBoolean = true
SomeArray = { 1, 2, 3 }
Day = Monday

[Person]
Name = Peter
Age = 50

在这里插入图片描述

3.读取配置文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleTest
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

using ConsoleTest;
using SharpConfig;

var config = Configuration.LoadFromFile("sample.cfg");
var section = config["General"];

string someString = section["SomeString"].StringValue;
int someInteger = section["SomeInteger"].IntValue;
float someFloat = section["SomeFloat"].FloatValue;
bool someBool = section["SomeBoolean"].BoolValue;
int[] someIntArray = section["SomeArray"].IntValueArray;
string[] someStringArray = section["SomeArray"].StringValueArray;
DayOfWeek day = section["Day"].GetValue<DayOfWeek>();

// Entire user-defined objects can be created from sections and vice versa.
var person = config["Person"].ToObject<Person>();
Console.WriteLine("读取完成");

在这里插入图片描述
也可以使用循环读取

foreach (var section in myConfig)
{
    foreach (var setting in section)
    {
        // ...
    }
}

4.写入配置文件

写入配置文件以内存为主

// 创建配置文件
using SharpConfig;

var myConfig = new Configuration();

// 设置配置文件值
myConfig["Video"]["Width"].IntValue = 1920;
myConfig["Video"]["Height"].IntValue = 1080;
myConfig["Video"]["Formats"].StringValueArray = new[] { "RGB32", "RGBA32" };

// 读取配置文件
int width = myConfig["Video"]["Width"].IntValue;
int height = myConfig["Video"]["Height"].IntValue;
string[] formats = myConfig["Video"]["Formats"].StringValueArray;
Console.WriteLine("读取完成");

在这里插入图片描述

5.加载配置文件

Configuration.LoadFromFile("myConfig.cfg");        // Load from a text-based file.
Configuration.LoadFromStream(myStream);            // Load from a text-based stream.
Configuration.LoadFromString(myString);            // Load from text (source code).
Configuration.LoadFromBinaryFile("myConfig.cfg");  // Load from a binary file.
Configuration.LoadFromBinaryStream(myStream);      // Load from a binary stream.

6.保存配置

myConfig.SaveToFile("myConfig.cfg");        // Save to a text-based file.
myConfig.SaveToStream(myStream);            // Save to a text-based stream.
myConfig.SaveToBinaryFile("myConfig.cfg");  // Save to a binary file.
myConfig.SaveToBinaryStream(myStream);      // Save to a binary stream.
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);

7.忽略属性、字段和类型

class SomeClass
{
    public string Name { get; set; }
    public int Age { get; set; }

    [SharpConfig.Ignore]
    public int SomeInt { get; set; }
}

SharpConfig 现在在从 SomeClass 类型的对象创建节时将忽略 SomeInt 属性,反之亦然。

8.添加自定义对象转换器

在某些情况下,您可能希望根据特定要求为自定义类型实现转换规则。 这很简单,涉及两个步骤,使用人员示例进行说明:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

8.1 创建转换器

using SharpConfig;
public class PersonStringConverter : TypeStringConverter<Person>
{
    // This method is responsible for converting a Person object to a string.
    public override string ConvertToString(object value)
    {
        var person = (Person)value;
        return string.Format("[{0};{1}]", person.Name, person.Age);
    }

    // This method is responsible for converting a string to a Person object.
    public override object ConvertFromString(string value, Type hint)
    {
        var split = value.Trim('[', ']').Split(';');

        var person = new Person();
        person.Name = split[0];
        person.Age = int.Parse(split[1]);

        return person;
     }
}

8.2 注册类型转换

using SharpConfig;
Configuration.RegisterTypeStringConverter(new PersonStringConverter());

每当在设置上使用 Person 对象(通过 GetValue() 和 SetValue())时,您的转换器是 选择以处理转换。 这也会自动与数组的 SetValue() 和 GetValueArray() 一起使用。

9.对象和数组操作

//--------------------对象操作--------------------------------
var cfg = new Configuration();
//对象.
var p = new SomeClass    
{      
    SomeString = "foobar",      
    SomeInt = 2000,      
    SomeInts = new[] { 1, 2, 3 },      
    SomeDate = DateTime.Now    
};
//设置
cfg.Add(Section.FromObject("SomeStructure", p));
//--------------------数组操作--------------------------------

var cfg = new Configuration();cfg["GeneralSection"]["SomeInts"].IntValueArray = new[] { 1, 2, 3 };
// 获取数组类型值
int[] someIntValuesBack = cfg["GeneralSection"]["SomeInts"].GetValueArray<int>();
float[] sameValuesButFloats = cfg["GeneralSection"]["SomeInts"].GetValueArray<float>();
string[] sameValuesButStrings = cfg["GeneralSection"]["SomeInts"].GetValueArray<string>();
// 获取数组对象
object[] sameValuesButObjects = cfg["GeneralSection"]["SomeInts"].GetValueArray(typeof(int));

10.文件注释


//获取包含所有有效注释分隔字符的数组。当前值为{“#”,“;”}。
Configuration.ValidCommentChars{get;//获取或设置保存配置时的首选注释字符。默认值为“#”。
Configuration.PreferredCommentChar{get;set;//获取或设置设置的数组元素分隔符。默认值为“,”。
Configuration.ArrayElementSeparator{get;set;//获取或设置一个值,该值指示在分析配置时是否应忽略内联注释。
bool Configuration.IgnoreInlineComments{get;set;//获取或设置一个值,该值指示在分析配置时是否应忽略前置注释。
bool Configuration.IgnorePreComments{get;set;//获取或设置一个值,该值指示在创建配置时是否应添加等号之间的空格。
bool Configuration.SpaceBetweenEquals{get;set;//获取或设置一个值,该值指示字符串值是否不带引号,但包括其间的所有内容
bool Configuration.OutputRawStringValues{get;set;

备注

有时项目有特殊的配置文件或其他需求,例如忽略文件中的所有注释。 为了获得更大的灵活性,可以使用 Configuration 类的静态属性修改 SharpConfig 的行为。 以下属性是当前属性:

1、CultureInfo Configuration.CultureInfo { get; set; }

  • 获取或设置用于 SharpConfig 中的值转换的区域性信息。默认值为CultureInfo.InvariantCulture。

2、 char[] Configuration.ValidCommentChars { get; }

  • 获取包含所有有效注释分隔字符的数组。当前值为 { ‘#’, ‘;’ }。

3、char Configuration.PreferredCommentChar { get; set; }

  • 获取或设置保存配置时的首选注释字符。默认值为“#”。

4、char Configuration.ArrayElementSeparator { get; set; }

  • 获取或设置设置的数组元素分隔符。默认值为“,”。
  • 请记住,在 Set 实例存在时更改此值后,期望其 ArraySize 和其他与数组相关的值返回不同的值。

5、bool Configuration.IgnoreInlineComments { get; set; }

  • 获取或设置一个值,该值指示在分析配置时是否应忽略内联注释。

6、bool Configuration.IgnorePreComments { get; set; }

  • 获取或设置一个值,该值指示在分析配置时是否应忽略预注释。

7、bool Configuration.SpaceBetweenEquals { get; set; }

  • 获取或设置一个值,该值指示在创建配置时是否应添加等于之间的空格。

8、bool Configuration.OutputRawStringValues { get; set; }

  • 获取或设置一个值,该值指示字符串值是否不带引号,但包括介于两者之间的所有内容。例:
    • 该设置将写入 as 中的文件MySetting=" Example value"MySetting= Example value
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/aa2528877987/article/details/128698597