Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello All,

I am stuck on some file reading code. I have a FileStream and StreamReader variables and am looping through reading a file. Now where I am stuck is once I find a certain line in the file I want to read 2 more lines and see if that second line is what I am looking for. If not, I want to be able to go back to where I was last in the file before moving ahead 2 more lines. For example, if I read the 10th line and it has "class=myAnswer" in the text of that line, then I want to read 2 more lines in the file. Once I then look at line 12 and it does not contain "class=myReference", then I want the file reading pointer to essentially go back to line 10 of the file so that when this routine ends then the next routine that reads will end up moving forward to line 12 to use that line that it needs.
I tried to use myFileStream.Seek(-2,SeekOrigin.Current) and that did not work. Any ideas on what to do?

Thanks In Advance,

Brad
Posted
Comments
BoxyBrown 10-Aug-11 11:02am    
You mean that 11th line can also contain "class=myAnswer" and if you fail with 12th line (checking condition "calss=myReference") you should analyse 11th and 13th lines pair?
clugsy64 10-Aug-11 11:11am    
No, the 11th line will just be an empty line. Once I read the 10th line and it has "class=myAnswer", the 11th line will be empty so I want to read the 12th line. This 12th line may contain "class=myReference" and it may not. If it does, then I will read the rest of it and then continue moving forward. However, if it does not contain "class=myReference" then the next routine that reads the file actually needs the 12th line I just read. So that things do not get out of order, I then need to tell the pointer to go back so that the next .ReadLine() will read the 11th (which is empty) and then the 12th to get what is needed.

Any ideas?
BoxyBrown 10-Aug-11 11:50am    
How do you read lines? You use StreamReader?
clugsy64 10-Aug-11 11:55am    
Yes, I use StreamReader

1 solution

Does this file change during your processing? If not you could use ReadLine to place each one in a string array then you could easily go through the array by index position.

List<string> lines = new List<string>();
while(string line = reader.ReadLine() != null)
{
  lines.Add(line);
}

for(int x = 0; x < lines.Count; x++)
{
   if(lines[x].Contains(...))
   {
     if(!CheckLine(lines[x+2]) )
     {
       X+=2;
     }
   }
}


(Didn't run this through the compile but you get the idea)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900