You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何读取键值对格式配置文件并转换为Dictionary?

读取简化键值对配置文件的简便方法

这种配置文件属于无分区的键值对格式,是INI配置的简化版,不用纠结具体名称,不管自己写轻量解析还是用现成库都能快速转成字典/对象,下面给你两种实用方案:

方案1:手动写轻量解析(快速解决需求)

拿Python举例,几行代码就能把文件转成字典,还能自动处理数字和带引号的字符串:

config_dict = {}
with open('你的配置文件名.txt', 'r') as f:
    for line in f:
        line = line.strip()
        # 跳过空行和注释(如果有需要可以保留这行)
        if not line or line.startswith('#'):
            continue
        # 按第一个等号拆分键和值
        key, value = line.split('=', 1)
        key = key.strip()
        value = value.strip()
        # 去掉字符串的引号
        if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
            value = value[1:-1]
        # 尝试把值转成数字
        try:
            value = int(value)
        except ValueError:
            try:
                value = float(value)
            except ValueError:
                pass  # 转不成数字就保留字符串
        config_dict[key] = value

之后直接用config_dict.get('ValueA')取值,或者用'ValueA' in config_dict检查键是否存在就行。

方案2:用现成库省事儿

Python:用configparser

这个库原本是处理带分区的INI文件,但可以加个虚拟分区适配你的格式:

import configparser
config = configparser.ConfigParser()
# 给配置内容加个虚拟分区,让configparser能识别
with open('你的配置文件名.txt', 'r') as f:
    config.read_string('[temp_section]\n' + f.read())
# 转成字典
config_dict = dict(config['temp_section'])
# 按需转类型
for k, v in config_dict.items():
    try:
        config_dict[k] = int(v)
    except ValueError:
        pass

C#:用Microsoft.Extensions.Configuration

在.NET项目里可以直接用官方的配置包,支持直接读取这种格式:

using Microsoft.Extensions.Configuration;

var configBuilder = new ConfigurationBuilder()
    .AddIniFile("你的配置文件名.txt", optional: false, reloadOnChange: true);
var config = configBuilder.Build();

// 直接读取指定键的值
int valueA = config.GetValue<int>("ValueA");
string someText = config["SomeText"];

// 转成字典
var configDict = config.AsEnumerable()
    .ToDictionary(kv => kv.Key, kv => kv.Value);

额外提示

如果之后需要更复杂的配置(比如嵌套结构、数组),可以考虑转成JSON或YAML,但当前这种简单键值格式用上面的方法完全够用。

内容的提问来源于stack exchange,提问作者Mathijs van Nimwegen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:08:13