SKIP从平面文件中读取第150行

时间:2012-02-03 21:35:53

标签: c# .net-3.5

我确实查找了旧帖子,但这似乎没有用.......我想基本上跳过先阅读150行....

using (StreamReader stream = new StreamReader(FileInfo.FullName)) 
{ 
    string line; 
    while(!stream.EndOfStream) 
    { 
        for (int i = 1; i >= 150; i++) 
        { 
            line = stream.ReadLine(); 
        } 
    }  
}

谢谢,

5 个答案:

答案 0 :(得分:5)

using (StreamReader stream = new StreamReader(FileInfo.FullName)) 
{ 
    string line; 
    int i = 0;
    while(!stream.EndOfStream) 
    { 
         i++;
         line = stream.ReadLine();
         if ( i <= 150 ) continue;

         // Do something with the line. 
    }  
}

答案 1 :(得分:0)

你正在运行你的循环试图读取150行,直到你到达流的末尾,并且你的条件反转,它应该是&lt; = 150,所以你实际上没有读取任何行。< / p>

bool SkipLines(StreamReader reader, int line_cnt) 
{
   for (int i = 0; i < line_cnt; i++) {
      String line = stream.ReadLine(); 
      if(line == null) {
         return false;
   }
  return true;
}

并称之为例如。

using (StreamReader stream = new StreamReader(FileInfo.FullName)) {
   if(!SkipLines(stream, 150)) {
      return; //or do whatever you need to if when the file contained less
              //than 150 lines

 ... process rest of file
}

答案 2 :(得分:0)

如果您不担心将整个文件加载到内存中,最简单的方法可能只是这样做:

var theRest = File.ReadAllLines(filename).Skip(150).ToList();

答案 3 :(得分:0)

using (StreamReader stream = new StreamReader(FileInfo.FullName)) 
{ 
    string line; 
    int i = 0;
    while(!stream.EndOfStream && (i++ <= 150)) 
    { 
         line = stream.ReadLine();
    }  
}

答案 4 :(得分:0)

从.BIN文件中逐行读取非常简单。如果你想通过改变while循环中的条件只读取前150行。

FileStream fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read);
            using (StreamReader stream = new StreamReader(fs))
            {
                string line;
                int i = 0;

                while (!stream.EndOfStream && (i++ >= 0))//for neglecting first 150 rows the condition will be (i++ <= 150) try this.I hope it helps.
                {
                    line = stream.ReadLine();
                }
            }