简体   繁体   中英

How to skip txt file chunks

How do I skip reading the file at the red boxes only to continue reading the file at the blue boxes? What adjustments would I need to make to 'fileReader'?

So far, with the help of SO users, I've been able to successfully skip the first 8 lines (first red box) and read the rest of the file. But now I want to read ONLY the parts indicated in blue.

I'm thinking of making a method for each chunk in blue. Basically start it by skipping first 8 lines of file if its first blue box, about 23 for the next blue box but ending the file reader is where I'm having problems. Simply don't know what to use.

在此处输入图片说明

private void button1_Click(object sender, EventArgs e)
{
    // Reading/Inputing column values

    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        string[] lines = File.ReadAllLines(ofd.FileName).Skip(8).ToArray();
        textBox1.Lines = lines;

        int[] pos = new int[3] {0, 6, 18}; //setlen&pos to read specific colmn vals
        int[] len = new int[3] {6, 12, 28}; // only doing 3 columns right now

        foreach (string line in textBox1.Lines)
        {
            for (int j = 0; j < 3; j++) // 3 columns
            {
                val[j] = line.Substring(pos[j], len[j]).Trim(); 
                list.Add(val[j]); // column values stored in list
            }
        } 
    }
}

Try something like this:

using System.Text.RegularExpressions;  //add this using

foreach (string line in lines)
{
    string[] tokens = Regex.Split(line.Trim(), " +");
    int seq = 0;
    DateTime dt;
    if(tokens.Length > 0 && int.TryParse(tokens[0], out seq))
    { 
        // parse this line - 1st type
    }
    else if (tokens.Length > 0 && DateTime.TryParse(tokens[0], out dt))
    {
        // parse this line - 2nd type
    }
    // else - don't parse the line
}

The Regex split is handy to break on any spaces till the next token. The Regex " +" means match one or more spaces. It splits when it finds something else. Based on your example, you only want to parse lines that begin with a number or a date, which this should accomplish. Note that I trimmed the line of leading and trailing spaces so that you don't split on any of those and get empty string tokens.

I can see what you want to read anything what:

  1. between line ending with Numerics (possible one line after)
  2. until line starting with 0Total (is that zero, right?);
  3. between line ending with CURREN
  4. until line with 1 as first symbol in the row.

Shouldn't be hard. Read file by line. When (1) or (3) occurs, start generating until (2) or (4) correspondingly.

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