Hesham Hassanein

Hesham Hassanein

  • NA
  • 140
  • 16.1k

Taking a certain value from a different line in a text file

Sep 29 2016 1:06 PM

Hello,

I have a text file that has this structure:

123456789|2|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:55:35|x

1|2|3

4|5|6

END-OF-LINE

123456789|7|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:42:35|y

7|8|9

1|4|5

END-OF-LINE

Records

I want to take the value of the date which is in index 10 (24 Sep 2016 02:42:35)

and put it in a variable named y and then use it depending on the file structure

Sometimes the file only consists of this

123456789|2|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:55:35|x

1|2|3

4|5|6

END-OF-LINE

I made a snippet for this, using the help of your Answers, but now the value that is written in the variable y is always the same

how can i change it depending on the line i am reading from. In other words. If i am reading from this line:

123456789|2|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:55:35|x

Variable Y should equals 24 Sep 2016 02:55:35

else

If i am reading from this

123456789|7|3|4|2016-09-24-02:56:00|b|123|c|G|24 Sep 2016 02:42:35|y

Variable Y should equals 24 Sep 2016 02:42:35

Here is the snippet. Thanks in Advance

There is something wrong in the code that it is getting always the last value of y. Is the value y correctly taken from the file?
  1. var templines1 = File.ReadAllLines(fileName).ToList();  
  2.           var fields3 = templines1[0].Split('|');           
  3.   
  4.   while (currentLine1 < templines1.Count)  
  5.           {  
  6.               // Peek ahead for the END-OF-LINE to get the name of the file.  
  7.               int terminatorLine1 = templines1.IndexOf("END-OF-LINE", currentLine1);  
  8.   
  9.               if (terminatorLine1 <= 0) break// If not found, or no penultimate line  
  10.   
  11.               int penultimateLine1 = currentLine1;  
  12.   
  13.               //Console.WriteLine(fields3[0]);  
  14.                 
  15.                 
  16.               if (fields3[0].Length == 9)  
  17.               {  
  18.                   //Console.WriteLine("True");  
  19.                   var fields1 = templines1[penultimateLine1].Split('|');               // get the comma separated fields  
  20.                   y = fields1[10];  
  21.                   allY.Add(y);  
  22.                 //  var list = new List<int>(Enumerable.Range(0, 50));  
  23.   
  24.                     
  25.                 
  26.               }  
  27.               currentLine1 = terminatorLine1 + 1;  
  28.   
  29.           }  
 

Answers (5)