C#从日志文件中读取特定属性

时间:2017-12-03 19:42:26

标签: c# .net linq

在我的M.U.G.E.N锦标赛计划中,我想处理日志文件中的匹配结果,该文件由游戏创建。日志看起来像这样:

[Match 1]
totalmatches = 1
team1.1 = 
team2.1 = 
stage = stages/kowloon.def

[Match 1 Round 1]
winningteam = 1
timeleft = -1.00
p1.name = Knuckles the Echidna
p1.life = 269
p1.power = 0
p2.name = Shadow the Hedgehog
p2.life = 0
p2.power = 2684

[Match 1 Round 2]
winningteam = 2
timeleft = -1.00
p1.name = Knuckles the Echidna
p1.life = 0
p1.power = 1510
p2.name = Shadow the Hedgehog
p2.life = 586
p2.power = 2967

[Match 1 Round 3]
winningteam = 2
timeleft = -1.00
p1.name = Knuckles the Echidna
p1.life = 0
p1.power = 3000
p2.name = Shadow the Hedgehog
p2.life = 789
p2.power = 777

我想要的是处理最后一个winningteam属性以确定匹配的结果。实现这一目标的最有效方法是什么? (也许是LINQ)

1 个答案:

答案 0 :(得分:0)

您可以使用File.ReadLines返回行的枚举IEnumerable<string>

// string path contains file path and file name.
string line = File.ReadLines(path)
    .LastOrDefault(ln => ln.StartsWith("winningteam ="));

现在将字符串拆分为=,修剪第二部分并将团队编号作为字符串

if (line != null) {
    string team = line.Split('=')[1].Trim();
    // With "winningteam = 2", [0] = "winningteam ", [1] = " 2"

    // Optionally convert it to a number
    int teamNo = Int32.Parse(team);

    ...
}