【问题标题】:Read ini sections with no values and append it to a dictionary读取没有值的 ini 部分并将其附加到字典中
【发布时间】:2020-06-27 12:12:54
【问题描述】:

我有以下带有节和键但没有指定值的 ini 文件:

[core]
bul_gravel_heli
ent_dst_concrete_large
bul_wood_splinter

[cut_armenian1]
cs_arm2_muz_smg
cs_ped_foot_dusty

我想做的是:

  • 阅读所有章节和价值。

  • 按以下格式将它们存储在字典中:

{section: {key1, key2, key3, key4, etc}

现在的问题是我在任何地方都找不到没有值的 ini 文件读取示例,我找到的所有结果都是读取没有节的 ini 文件。

  • 简要说明我想对存储的字典做什么:

    • 有一个函数public void AddList(string listName, List<dynamic> list),我要为每个字典键和值创建方法。我已经知道我可以使用 for 循环,但我一直在解析 ini 文件。

【问题讨论】:

  • 您尝试过哪些不起作用的方法?

标签: c# ini


【解决方案1】:

嗯,一个简单的foreach 循环应该可以:

private static Dictionary<string, List<string>> IniToDictionary(IEnumerable<string> lines) {
  Dictionary<string, List<string>> result = 
    new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);

  string category = "";

  foreach (string line in lines) {
    string record = line.Trim();

    if (string.IsNullOrEmpty(record) || record.StartsWith("#"))
      continue;
    else if (record.StartsWith("[") && record.EndsWith("]")) 
      category = record.Substring(1, record.Length - 2);
    else {
      int index = record.IndexOf('=');

      string name = index > 0 ? record.Substring(0, index) : record;

      if (result.TryGetValue(category, out List<string> list))
        list.Add(name);
      else
        result.Add(category, new List<string>() { name});
    }
  }

  return result;
}

如果要处理文件:

Dictionary<string, List<string> result = IniToDictionary(File
  .ReadLines(@"c:\MyIniFile.ini"));

让我们看看(测试输入):

Console.Write(tring.Join(Environment.NewLine, result
  .Select(pair => $"{pair.Key,-15} : [{string.Join(", ", pair.Value)}]")));

结果:

core            : [bul_gravel_heli, ent_dst_concrete_large, bul_wood_splinter]
cut_armenian1   : [cs_arm2_muz_smg, cs_ped_foot_dusty]

【讨论】:

    猜你喜欢
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2021-10-23
    • 2016-04-19
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多