【问题标题】:How to parse INI file?如何解析INI文件?
【发布时间】:2020-07-26 01:51:32
【问题描述】:

我有包含来自服务器的数据的 ini 文件。

地图.ini

[MAP_1]
MapType = 1
MapWar = 1
Position = 42.03,738.2,737.3

[MAP_2]
MapType = 1
MapWar = 1
Position = 42.03,738.2,737.3

如何读取包含此类文件的map.ini并将其保存在字典或列表中。

【问题讨论】:

  • 您可以将这些文件作为文本文件读取并逐行解析内容并将它们存储在字典中。
  • 由于键重复,我无法将其添加到字典中
  • 你能分享你的代码吗?
  • 请多指教

标签: c# ini


【解决方案1】:

尝试以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            List<Map> maps = new List<Map>();
            Map map = null;
            StreamReader reader = new StreamReader(FILENAME);
            string line = "";
            while ((line = reader.ReadLine()) != null)
            {
                line.Trim();
                if (line.Length > 0)
                {
                    if(line.StartsWith("["))
                    {
                        string name = line.Trim(new char[] { '[', ']' });
                        map = new Map();
                        maps.Add(map);
                        map.name = name;
                    }
                    else
                    {
                        string[] data = line.Split(new char[] { '=' });
                        switch (data[0].Trim())
                        {
                            case "MapType" :
                                map.mapType = int.Parse(data[1]);
                                break;
                            case "MapWar":
                                map.mapWar = int.Parse(data[1]);
                                break;
                            case "Position":
                                string[] numbers = data[1].Split(new char[] { ',' });
                                map.x = decimal.Parse(numbers[0]);
                                map.y = decimal.Parse(numbers[1]);
                                map.z = decimal.Parse(numbers[2]);
                                break;
                            default :
                                break;
                        }
                    }
                }
            }
            Dictionary<string, Map> dict = maps
                .GroupBy(x => x.name, y => y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
    public class Map
    {
        public string name { get; set; }
        public int mapType { get; set; }
        public int mapWar { get; set; }
        public decimal x { get; set; }
        public decimal y { get; set; }
        public decimal z { get; set; }
    }
}

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 2011-09-04
    • 2019-03-09
    • 1970-01-01
    • 2015-10-13
    • 2015-03-28
    • 1970-01-01
    • 2014-09-03
    相关资源
    最近更新 更多