读取两行文件,然后返回 [英] Read Two Lines Of File And Then Go Back

查看:76
本文介绍了读取两行文件,然后返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我被一些文件读取代码卡住了.我有一个FileStream和StreamReader变量,并且正在循环读取文件.现在,卡住的地方是一旦我在文件中找到某一行,我想再读取2行,看看第二行是否正是我要查找的行.如果没有,我希望能够返回文件的最后位置,然后再前进2行.例如,如果我阅读了第十行,并且该行的文本中包含"class = myAnswer",那么我想在文件中再读取2行.然后,当我查看第12行并且它不包含"class = myReference"时,我希望文件读取指针实质上回到文件的第10行,以便当该例程结束时,下一个读取的例程将结束前进至第12行以使用所需的行.
我尝试使用myFileStream.Seek(-2,SeekOrigin.Current),但没有用.关于该怎么办的任何想法?

在此先感谢,

Brad

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

推荐答案

在处理过程中此文件是否更改?如果没有,则可以使用ReadLine将每个字符串放置在一个字符串数组中,然后可以轻松地按索引位置遍历该数组.

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)


这篇关于读取两行文件,然后返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆