首页 > 解决方案 > 如何解析INI文件?

问题描述

我有包含来自服务器的数据的 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 并将其保存在 Dictionary 或 List 中。

标签: c#ini

解决方案


尝试以下:

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; }
    }
}

推荐阅读