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

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

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

项目简介

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

技术架构

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

项目结构

图片

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

更多开源项目请查看一个专注推荐优秀.Net开源项目的榜单

- End -

文章首发于公众号【编程乐趣】,欢迎大家关注。
图片

posted @ 2023-04-04 12:13  chingho  阅读(1226)  评论(4编辑  收藏  举报