FlatKeyValueConfiguration 1.0.0
dotnet add package FlatKeyValueConfiguration --version 1.0.0
NuGet\Install-Package FlatKeyValueConfiguration -Version 1.0.0
<PackageReference Include="FlatKeyValueConfiguration" Version="1.0.0" />
<PackageVersion Include="FlatKeyValueConfiguration" Version="1.0.0" />
<PackageReference Include="FlatKeyValueConfiguration" />
paket add FlatKeyValueConfiguration --version 1.0.0
#r "nuget: FlatKeyValueConfiguration, 1.0.0"
#:package FlatKeyValueConfiguration@1.0.0
#addin nuget:?package=FlatKeyValueConfiguration&version=1.0.0
#tool nuget:?package=FlatKeyValueConfiguration&version=1.0.0
FlatKeyValueConfiguration
一个面向 .NET 的扁平化键值配置格式。比 INI 更简单,也比 INI 更严谨。
动机
现有配置格式要么过于宽松(INI,无数方言与转义规则),要么过重(JSON / YAML / TOML,带嵌套、类型与引号)。
FlatKeyValueConfiguration 选择另一条路:
- 扁平。 一个键、一个值、一行。没有嵌套、没有数组、没有引用。
- 无类型。 文件里的值都是字符串。类型解释放在读取时,由调用方决定。
- 简单但严格。 只有四条基础规则,但决不接受无效输入。
- 有序。 注释、空行、键顺序在加载和存储后保持不变。
最终得到的,是一个可以像纯文本一样阅读、diff、合并的格式,同时在你需要时提供类型化 API
(Get<T> / Set<T> / Update<T>)。
格式规则
配置文件应使用 UTF8(无 BOM)进行存储,并严格遵循以下四条基础规则:
- 无类型。 每个值都是字符串。
- 键区分大小写。
Host与host是两个不同的键。 - 键和值自身之外的空白字符全部忽略。 键和值内部的空白字符原样保留。空白的值视作空字符串。
- 注释以
#开始,且必须独占一行。 不支持行尾注释。注释前后的空白字符会被忽略。
每条非注释、非空行的键值对形式如下:
key = value
等号 = 是必需的,不可省略,但值可以为空。例如 key = 是合法的,此时存储的值为空字符串。
只有键、没有 = 的行会被视为解析错误。
空行是合法的;空行不携带任何键值数据,只作为布局存在,并在加载和保存时被原样保留。
示例
# 服务器
host = localhost
port = 5432
# 功能开关
enable-cache = true
theme = dark
# 允许空值
optional-note =
快速开始
using FlatKeyValueConfiguration;
var cfg = await FkvCfg.LoadAsync("app.cfg");
// 类型化读取。FkvCfg 默认提供了 bool、所有整型、float、double 类型的默认转换方法。
string host = cfg.Get("host");
int port = cfg.Get("port");
bool debug = cfg.Get("debug", false);
// 仅更新:键不存在时返回 false。
if (!cfg.Update("port", 8080))
Console.WriteLine("port 未配置");
// Upsert:键不存在则新增,存在则更新。
cfg.Set("theme", "light");
await cfg.SaveAsync("app.cfg");
API
static Task<FkvCfg> FkvCfg.LoadAsync(string path, int possibleCount = 1024)
加载文件。无法解析的行或重复出现的键会抛出 FormatException。possibleCount 仅作为内部集合的容量提示。
Task FkvCfg.SaveAsync(string path)
将配置写回磁盘。原有布局(空行、注释、键顺序)保持不变。文件以覆盖方式重写。
T Get<T>(string key, T defaultValue = default, StrToTypeParser<T> parser = null)
返回解析后的值;失败(键不存在或解析失败)时返回 defaultValue。
关于
defaultValue的契约:
null不是合法的存储值,因此也不能作为合法的回退值。- 对引用类型而言,省略
defaultValue等价于声明 "调用方保证该键存在且能成功解析",否则会抛出ArgumentNullException。- 对值类型而言,省略即得到
default(T)。
T Get<T>(string key, out FkvGetResult opResult, T defaultValue = default, StrToTypeParser<T> parser = null)
同上,但通过 opResult 报告结果(Success / KeyNotFound / ParseFail)。
bool Set<T>(string key, in T value, Func<T, string> toStr = null)
更新或新增。键原本存在时返回 true(更新),不存在时返回 false(新增)。
bool Update<T>(string key, in T value, Func<T, string> toStr = null)
仅更新。键存在并更新成功返回 true;否则返回 false,不会新增键。
FkvCfg(ICollection<KeyValuePair<string, string>> configs, ICollection<string> keysOrder = null)
构造函数。通过 configs 初始化实例。keysOrder 指定了 configs 中提供的键的顺序,它的数量必须和configs提供的键的数量一致,键名也必须对应。
如果 keysOrder 是 null,则顺序以 configs 提供的顺序为准。
自定义解析器与转换器
前面中API出现的参数 parser 与 toStr 按类型注册,对某个 T 传入一次之后, 后续调用可省略:
DateTime start = cfg.Get("start", DateTime.MinValue, DateTime.TryParse);
DateTime end = cfg.Get("end", DateTime.MaxValue); // 复用 DateTime.TryParse
cfg.Set("start", DateTime.UtcNow, d => d.ToString("O"));
cfg.Set("end", DateTime.UtcNow.AddHours(1)); // 复用 "O" 格式
注意:传入的解析器和转换器会覆盖旧有的转换器,假如它确实存在。 这个设计符合配置文件的典型情形:一个类型通常只有一种规范表示。
键与值的合法性
所有写入路径都会校验键与值;非法输入抛出 ArgumentException 。
合法键
- 非空。
- 不以
#开头。 - 首尾无空白字符。
- 任意位置不含
CR、LF。 - 至多含一个
=;若存在,必须位于首位。(仅由一个=组成的键也是合法的。)
合法值
- 不为
null("无值"请用空字符串表达)。 - 空字符串是合法的。
- 首尾无空白字符。
- 任意位置不含
CR、LF。
与集合接口的互操作:IDictionary 与 IList
FkvCfg 实现了 IDictionary<string, string> 与 IList<KeyValuePair<string, string>>,但两者都是
显式实现,不出现在类型的公开面上。
它们是为了在 FkvCfg 确实需要 “尽到一个有序字典应尽的义务” 时(例如作为参数传给泛型方法、适配到某个集合 API),能够履约:
IDictionary<string, string> dict = cfg;
// 按 IDictionary 的契约执行 upsert
dict["key"] = "value";
IList<KeyValuePair<string, string>> list = cfg;
list.Insert(0, new KeyValuePair<string, string>("first", "1"));
// foreach 通过 C# 模式匹配与 IEnumerable<KeyValuePair<,>> 直接可用,且保持添加顺序。
foreach (var kv in cfg)
Console.WriteLine($"{kv.Key} = {kv.Value}");
日常使用请选择公开的方法。只有在确实需要字典或列表契约时,才显式转换到相应接口。
备注
- 线程安全:
FkvCfg不保证线程安全,多线程并发修改时请自行同步。 - 编码: 读写均为 UTF-8(无 BOM)。
- 换行符:
LoadAsync接受\r\n、\n、\r三种;SaveAsync使用平台默认换行。
<br>
FlatKeyValueConfiguration
A flat key/value configuration format for .NET. Simpler than INI, and stricter than INI.
Motivation
Existing configuration formats are either too permissive (INI, with its countless dialects and escaping rules) or too heavy (JSON / YAML / TOML, with nesting, types, and quoting). FlatKeyValueConfiguration takes a different path:
- Flat. One key, one value, one line. No nesting, no arrays, no references.
- Untyped. Every value in the file is a string. Type interpretation is deferred to read time and decided by the caller.
- Simple but strict. Only four fundamental rules, but invalid input is never accepted.
- Ordered. Comments, blank lines, and key order are preserved across load and save.
The result is a format that reads, diffs, and merges like plain text, while offering a typed API (Get<T> / Set<T> / Update<T>) when you need one.
Format Rules
Configuration files should be stored as UTF-8 (without BOM) and must strictly follow these four fundamental rules:
- Untyped. Every value is a string.
- Case-sensitive keys.
Hostandhostare two different keys. - Whitespace outside the key and value is ignored. Whitespace inside the key and value is preserved verbatim. A whitespace-only value is treated as the empty string.
- Comments start with
#and must occupy an entire line. Inline (trailing) comments are not supported. Whitespace before and after a comment is ignored.
Each non-comment, non-blank line has the following key/value form:
key = value
The = sign is required and cannot be omitted, but the value may be empty. For example, key = is valid, and the stored value is the empty string.
A line that contains a key but no = is a parse error.
Blank lines are valid; they carry no key/value data, exist only as layout, and are preserved verbatim across load and save.
Example
# Server
host = localhost
port = 5432
# Feature flags
enable-cache = true
theme = dark
# Empty value allowed
optional-note =
Quick Start
using FlatKeyValueConfiguration;
var cfg = await FkvCfg.LoadAsync("app.cfg");
// Typed reads. FkvCfg provides default converters for bool, all integer types, float, and double.
string host = cfg.Get("host");
int port = cfg.Get("port");
bool debug = cfg.Get("debug", false);
// Update-only: returns false if the key does not exist.
if (!cfg.Update("port", 8080))
Console.WriteLine("port is not configured");
// Upsert: adds the key if missing, updates it otherwise.
cfg.Set("theme", "light");
await cfg.SaveAsync("app.cfg");
API
static Task<FkvCfg> FkvCfg.LoadAsync(string path, int possibleCount = 1024)
Loads a file. Unparseable lines or duplicate keys throw FormatException. possibleCount is only a capacity hint for the internal collections.
Task FkvCfg.SaveAsync(string path)
Writes the configuration back to disk. The original layout (blank lines, comments, key order) is preserved. The file is truncated and overwritten.
T Get<T>(string key, T defaultValue = default, StrToTypeParser<T> parser = null)
Returns the parsed value; on failure (missing key or parse failure) it returns defaultValue.
Contract on
defaultValue:
nullis not a valid stored value, and therefore cannot be a valid fallback either.- For reference types, omitting
defaultValuedeclares that "the caller guarantees the key exists and parses"; otherwise anArgumentNullExceptionis thrown.- For value types, omitting it yields
default(T).
T Get<T>(string key, out FkvGetResult opResult, T defaultValue = default, StrToTypeParser<T> parser = null)
Same as above, but reports the outcome through opResult (Success / KeyNotFound / ParseFail).
bool Set<T>(string key, in T value, Func<T, string> toStr = null)
Update or add. Returns true if the key already existed (update), false if it was newly added.
bool Update<T>(string key, in T value, Func<T, string> toStr = null)
Update-only. Returns true if the key existed and was updated; otherwise returns false, and no key is added.
FkvCfg(ICollection<KeyValuePair<string, string>> configs, ICollection<string> keysOrder = null)
Constructor. Initializes an instance from configs. keysOrder specifies the ordering of the keys provided in configs; its count must match the number of keys provided by configs, and the key names must correspond.
If keysOrder is null, the order follows the order provided by configs.
Custom Parsers and Converters
The parser and toStr parameters that appear in the API above are registered per type. Once supplied for a given T, they can be omitted in subsequent calls:
DateTime start = cfg.Get("start", DateTime.MinValue, DateTime.TryParse);
DateTime end = cfg.Get("end", DateTime.MaxValue); // reuses DateTime.TryParse
cfg.Set("start", DateTime.UtcNow, d => d.ToString("O"));
cfg.Set("end", DateTime.UtcNow.AddHours(1)); // reuses the "O" format
Note: a supplied parser or converter overrides any previously registered one, if one already exists. This design matches the typical configuration-file scenario: a type usually has only one canonical representation.
Key and Value Validity
Every write path validates keys and values; invalid input throws ArgumentException.
Valid Key
- Non-empty.
- Does not start with
#. - No leading or trailing whitespace.
- No
CRorLFanywhere. - Contains at most one
=; if present, it must be the first character. (A key consisting of a single=is also valid.)
Valid Value
- Not
null(use the empty string to express "no value"). - The empty string is valid.
- No leading or trailing whitespace.
- No
CRorLFanywhere.
Interoperability with Collection Interfaces: IDictionary and IList
FkvCfg implements IDictionary<string, string> and IList<KeyValuePair<string, string>>, but both are explicitly implemented and do not appear on the public surface of the type.
They exist so that FkvCfg can honor its obligations when it genuinely needs to "fulfill the obligations of an ordered dictionary" (for example, being passed as an argument to a generic method or adapted to some collection API):
IDictionary<string, string> dict = cfg;
// performs upsert per the IDictionary contract
dict["key"] = "value";
IList<KeyValuePair<string, string>> list = cfg;
list.Insert(0, new KeyValuePair<string, string>("first", "1"));
// foreach works directly via C# pattern matching and IEnumerable<KeyValuePair<,>>, and preserves insertion order.
foreach (var kv in cfg)
Console.WriteLine($"{kv.Key} = {kv.Value}");
For everyday use, prefer the public methods. Only cast explicitly to the relevant interface when you actually need the dictionary or list contract.
Notes
- Thread safety:
FkvCfgis not thread-safe; synchronize externally when mutating it concurrently from multiple threads. - Encoding: Reads and writes use UTF-8 (without BOM).
- Line endings:
LoadAsyncaccepts\r\n,\n, and\r;SaveAsyncuses the platform default.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0 | 79 | 11/7/2026 |