读取文本文件时忽略页眉和页脚行

时间:2012-05-14 14:24:46

标签: c#

到目前为止,这是我的代码:

string _nextLine;
string[] _columns;
char[] delimiters;

delimiters = "|".ToCharArray();

using (StreamReader _reader = ...)
{
    _nextLine = _reader.ReadLine();

    while (_nextLine != null)
    {
        _columns = _nextLine.Split(delimiters);
        JazzORBuffer.AddRow();
        JazzORBuffer.Server = _columns[0];
        JazzORBuffer.Country = _columns[1];
        JazzORBuffer.QuoteNumber = _columns[2];
        _nextLine = _reader.ReadLine();
    }
}

我文件的前5行如下:

PRODUCTS created betwen x and y

Column 1 Header | Columns 2 Header | Column 3 Header | Column 4 Header |

Wendy Z| Dave | John | Steve |

最后3行如下:

Wendy Z| Dave | John | Steve |

Total number of prods| 49545

我需要在代码中更改什么才能忽略文件中的前3行和最后一行?

1 个答案:

答案 0 :(得分:4)

我不是100%确定我理解这个问题,但请尝试:

string[] lines = File.ReadAllLines("FilePath");
string[] _columns;

//Start at index 2 - and keep looping until index Length - 2
for (int i = 2; i < lines.Length - 2; i++)
{
    _columns = lines[i].Split('|');
    JazzORBuffer.AddRow();
    JazzORBuffer.Server = _columns[0];
    JazzORBuffer.Country = _columns[1];
    JazzORBuffer.QuoteNumber = _columns[2];
}

注意 - 通过一次性将整个文件读入内存,这将改变您正在执行的操作的性能。如果它是一个非常大的文件,这可能不是高性能。如果是,请这样说:)

相关问题