一个.Net简单、易用的配置文件操作库

在我们日常项目开发中,操作INI/CFG配置文件,往往会通过调用WinAPI来实现,WinAPI接口参数只支持字符串,而我们项目中,往往数据类型是多种多样的,在保存和获取配置值,我们就要进行类型的转换。

今天给大家推荐一个操作库,这个库就可以解决我们的问题。

项目简介

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

技术架构

跨平台:这是基于.Netstandard2.0开发的系统,可以部署在Docker,Windows,Linux,Mac。

项目结构

一个.Net简单、易用的配置文件操作库

SharpConfig:配置库操作项目,Example:使用示例。

使用方法

文件加载

Configuration.LoadFromFile("myConfig.cfg");        // 文件Configuration.LoadFromStream(myStream);            // 文本流Configuration.LoadFromString(myString);            // 文本Configuration.LoadFromBinaryFile("myConfig.cfg");  // 二进制Configuration.LoadFromBinaryStream(myStream);      // 二进制流

文件保存

myConfig.SaveToFile("myConfig.cfg"); // 文件myConfig.SaveToStream(myStream); // 文件流myConfig.SaveToBinaryFile("myConfig.cfg");  // 二进制文件myConfig.SaveToBinaryStream(myStream); // 二进制流

使用方法

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

对象操作

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

配置文件注释

//获取包含所有有效注释分隔字符的数组。当前值为{“#”,“;”}。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;}

项目地址

https://github.com/cemdervis/sharpconfig