简体   繁体   中英

Ignore header and footer lines when reading a text file

This is my code so far:

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

The first 5 lines of my file look as follows:

PRODUCTS created betwen x and y

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

Wendy Z| Dave | John | Steve |

The last 3 lines look as follows:

Wendy Z| Dave | John | Steve |

Total number of prods| 49545

What do I need to change in my code so the first 3 lines and the last line in the file are ignored?

I'm not 100% sure I understand this question, but try:

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

Note - this will change the performance of what you're doing, by reading the whole file into memory in one go. If it's a very large file, this may not be performant. If it is, say so :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM