试图编写一个c#程序来解析文本文件,该文本文件包含用方括号中的标头分隔的数据

| 我写了一个程序来解析一个特定的文本文件,该文件中包含要稍后处理的数据。每个部分都用方括号中的标题隔开,我想知道如何使用标题作为数组的名称将每个段放入数组中。以下是文本文件开头的示例。香港专业教育学院建立了一个表格,让您选择要处理的文件,并且香港专业教育学院还建立了一种使用objReader.ReadLine在循环中逐行处理文件的方式
[Params]
Version=106
Monitor=34
SMode=111111100
Date=20090725
StartTime=13:56:44.0
Length=00:24:30.5
Interval=1
Upper1=0
Lower1=0
Upper2=0
Lower2=0
Upper3=0
Lower3=0
Timer1=00:00:00.0
Timer2=00:00:00.0
Timer3=00:00:00.0
ActiveLimit=0
MaxHR=180
RestHR=70
StartDelay=0
VO2max=51
Weight=0

[Note]
TT Warm Up

[IntTimes]
00:24:30.5  140 83  154 174
0   0   0   41  112 33
0   0   0   0   0
0   12080   0   280 0   0
0   0   0   0   0   0

[IntNotes]

[ExtraData]

[Summary-123]
1470    0   1470    0   0   0
180 0   0   70
1470    0   1470    0   0   0
180 0   0   70
0   0   0   0   0   0
180 0   0   70
0   1470

[Summary-TH]
1470    0   1470    0   0   0
180 0   0   70
0   1470

[HRZones]
180
162
144
126
108
90
0
0
0
0
0  
    
已邀请:
您可以使用类似这样的模式。
List<String> paramsList;
List<String> noteList;
List<String> tempList;

while (line = objReader.ReadLine()) {
    if (line.StartsWith(\"[\")) {

        // start new array
        if (line.Equals(\"[Params]\"))
            tempList = paramsList = new List<String>();
        else if (line.Equals(\"[Note]\"))
            tempList = noteList = new List<String>();

        // etc.

    } else if (String.IsNullOrEmpty(line)) {

        // ignore, end of array

    } else {

        // add element to array
        tempList.Add(line);

    }
}

// now use paramsList, noteList, etc. as needed
我不太清楚将标题用作数组名称的意思。所有文件的标头是否始终相同?您无法基于字符串动态分配变量的名称,如果以后需要使用它,也不会想要。     
我将其解析为字典:
    Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();

    using (StreamReader reader = new StreamReader(\"filename\"))
    {
        string token = null;
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (line.StartsWith(\"[\"))
                d[token] = new List<string>();
            else
                d[token].Add(line);
        }
    }
如果您有重复的令牌,上述方法还将添加数据行。     
由于此文件格式超出了常规INI文件的范围(请参阅Nicholas Carey的答案中David Yaw的评论),因此我将使用由解析器生成器创建的正确解析器。我选择的工具是GOLD Parser Builder,但是任何其他解析器生成器也可以执行。     

要回复问题请先登录注册