Question

I have a text file which contains lines that i need to process.Here is the format of the lines present into my text file..

07 IVIN  15:37 06/03 022  00:00:14 600        2265507967       0:03   

08 ITRS  15:37 06/03 022  00:00:09 603        7878787887       0:03

08 ITRS  15:37 06/03 022  00:00:09 603        2265507967       0:03 

Now as per my requirement i have to read this text file line by line.Now as soon as i get ITRS into any line i have to search for the number 2265507967 into the immediate upside of the text file lines.As soon as it gets 2265507967 in the upside lines ,it should read that line. Now i am reading the lines into strings and breaking into characters based on spaces.Here is my code..

var strings = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

My problem is that i am not getting way to traverse upside of the text file and search for the substring .i.e. 2265507967.Please help .

Was it helpful?

Solution

I am not aware of being able to go backwards when reading a file (other than using the seek() method) but I might be wrong...

A simpler approach would be to:

  1. Create a dictionary, key value being the long numeric values while the value being the line to which it belongs: <2265507967,07 IVIN 15:37 06/03 022 00:00:14 600 2265507967 0:03>

  2. Go through the file one line at a time and:

    a. If the line contains ITRS, get the value from the line and check your dictionary. Once you will have found it, clear the dictionary and go back to step 1.

    b. If it does not contain ITRS, simply add the number and the line as key-value pairs.

This should be quicker than going through one line at a time and also simpler. The drawback would be that it could be quite memory intensive.

EDIT: I do not have a .NET compiler handy, so I will provide some pseudo code to better explain my answer:

//Initialization
Dictionary<string, string> previousLines = new Dictionary<string, string>();
TextReader tw = new TextReader(filePath);
string line = String.Empty;

//Read the file one line at a time
while((line = tw.ReadLine()) != null)
{
    if(line.contains("ITRS")
    {
        //Get the number you will use for searching
        string number = line.split(new char[]{' '})[4];
        //Use the dictionary to read a line you have previously read.
        string line = previousLines[number];

        previousLines.Clear(); //Remove the elements so that they do not interrupt the next searches. I am assuming that you want to search between lines which are found between ITRS tags. If you do not want this, simply omit this line.
        ... //Do your logic here.
    }
    else 
    {
         string number = line.split(new char[]{' '})[4];
         previousLines.Add(number, line);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top