简体   繁体   English

使用StreamReader读取特定行

[英]Reading a specific line with StreamReader

I have a problem with the stream reader. 我的流阅读器有问题。 i want to read from a text file just one line. 我只想从一个文本文件中读取一行。

I want a specific line, like the seventh line. 我想要一个特定的行,例如第七行。 and i don't know how to. 而且我不知道该怎么做。

it's a function or something like that ? 是功能还是类似的东西? like file.ReadLine(number 7) ? 像file.ReadLine(number 7)吗?

The simplest approach would probably be to use LINQ combined with File.ReadLines : 最简单的方法可能是结合使用LINQ和File.ReadLines

string line = File.ReadLines("foo.txt").ElementAt(6); // 0-based

You could use File.ReadAllLines instead, but that would read the whole file even if you only want an early one. 可以改用File.ReadAllLines ,但这将读取整个文件,即使您只想要一个早期的文件。 If you need various different lines of course, it means you can read them in one go. 当然,如果您需要各种不同的路线,那意味着您可以一次性阅读它们。 You could write a method to read multiple specific lines efficiently (ie in one pass, but no more than one line at a time) reasonably easily, but it would be overkill if you only want one line. 您可以编写一种方法来相当容易地有效读取多个特定行(即,一次通过,但一次不超过一行),但是如果您只想一行,那将是多余的。

Note that this will throw an exception if there aren't enough lines - you could use ElementAtOrDefault if you want to handle that without any exceptions. 请注意,如果没有足够的行,这将引发异常-如果您想在没有任何异常的情况下进行处理,则可以使用ElementAtOrDefault

If you want to read line by number it's better to use 如果您想按行阅读,最好使用

string line = File.ReadLines(fileName).Skip(N).FirstOrDefault();

Thus you will avoid reading all lines from file, and you'll read lines only until you get line you need. 因此,您将避免读取文件中的所有行,并且仅读取行,直到获得所需的行为止。 If you need several lines, then it's better to read all lines to array, and then get your lines from that array: 如果需要几行,则最好将所有行读取到数组中,然后从该数组中获取行:

 string[] lines = File.ReadAllLines(fileName);

 if (lines.Count() > N)
     line = lines[N];

if you want to specific line by using StreamReader. 如果要使用StreamReader来指定特定行。 Suppose you have a data Line1,Line2,Line3,Line4 in text files. 假设文本文件中有数据Line1,Line2,Line3,Line4。 Every time you call "ReadLine" method it will increase 1 line. 每次调用“ ReadLine”方法时,它将增加1行。 That mean you can write you own function and passing your parmeter to function. 这意味着您可以编写自己的函数并将参数传递给函数。 You can do it by. 你可以做到的。

string l1, l2, l3, l4;
StreamReader sr = new StreamReader(sourcePath);
l1 = sr.Readline(); // Line 1
l2 = sr.Readline(); // Line 2
l3 = sr.Readline(); // Line 3


  public string StreamReadLine(string sourcepath, int lineNum)
    {
      int index = lineNum;
      string strLine = "N/A";
      StreamReader sr = new StreamReader(sourcepath);
     try
    {
       for (var i = 0; i <= index; i++)
       {
         strLine = sr.ReadLine();
         if (i == index)
             break;
         i += 1;
       }
   }
   catch (Exception ex)
   {
     strLine = ex.ToString();
   }
return strLine;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM