c# - 如何解析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 中。
解决方案
尝试以下:
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; }
}
}
推荐阅读
- selenium-ide - Selenium IDE 表和源选项卡
- c# - 如果其父对象是 VerticalLayoutGroup,则 Unity ui 对象无法对齐
- javascript - JavaScript Date.getTime()(毫秒)如何映射到 64 位浮点数?
- git - creact-react-app 忽略 github 中的 .gitignore
- python-2.7 - 使用python在完整行中搜索2个确切的字符串
- python - 如何使用类创建库存
- python - Plotly 值错误 - 颜色属性无效
- json - 如何在 TypeScript 中引用 JSON 文件?
- python - 为什么树迭代在 python 类中不能正常工作
- javascript - Angular 4:如何使用来自 Firebase 实时数据库的数据对 ngFor 列表进行排序