简体   繁体   English

从文本文件读取特定行的方法是什么?

[英]What's a way to read a specific line from a text file?

I want to read a line from a text file, except that I want to specify the line to read. 我想从文本文件中读取一行,但我想指定要读取的行。

I've tried: 我试过了:

using (StreamReader reader = new StreamReader(@"C:\\Program Files\\TTVB\\Users.txt")) 使用(StreamReader阅读器=新的StreamReader(@“ C:\\ Program Files \\ TTVB \\ Users.txt”))

  { text = reader.ReadLine(acctMade); } 

acctMade is an int. acctMade是一个int。

This returns: 返回:

No overload for method 'ReadLine' takes 1 arguments 方法'ReadLine'的重载没有1个参数

If the file is not that big, you can use File.ReadAllLines to put the file into a array of strings: 如果文件不是那么大,则可以使用File.ReadAllLines将文件放入字符串数组中:

string[] lines = File.ReadAllLines(@"C:\Program Files\TTVB\Users.txt");
Console.WriteLine(lines[acctMade]);

You need to use using System.IO; 您需要using System.IO;来使用using System.IO; at the top of your code or use System.IO.File.ReadAllLines in order for it to be usable. 在代码顶部,或使用System.IO.File.ReadAllLines使其可用。

A variety of ways: Read certain line in a text file (CodeProject 多种方法: 读取文本文件中的某些行(CodeProject

A simple way using StreamReader: 使用StreamReader的简单方法:

string GetLine(string fileName, int line)
{
   using (var sr = new StreamReader(fileName)) {
       for (int i = 1; i < line; i++)
          sr.ReadLine();
       return sr.ReadLine();
   }
}

Snippet from: How do I read a specified line in a text file? 摘录自: 如何读取文本文件中的指定行?

For a more efficient but complex way: 为了更有效但更复杂的方式:

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

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