从一行到另一行读取txt文件?

-6 .net c# text-files

需要一些函数来返回带有txt文件行的List(例如从10行到25行).有解决方案吗 我所有的尝试都遇到了失败.

Ser*_*kiy 10

您可以使用LINQ和File.ReadLines来枚举文件行(在内部它使用StreamReader):

List<string> lines = File.ReadLines(path).ToList();
Run Code Online (Sandbox Code Playgroud)


Dar*_*ren 5

你可以这样做:

List<string> fileLines = new List<string>();

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
       fileLines.Add(line);
    }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 5

// Retrieve 10 lines from Somefile.txt, starting from line 1
string filePath = "C:\\Somefile.txt";
int startLine = 1;
int lineCount = 10;
var fileLines = System.IO.File.ReadAllLines(filePath)
                .Skip((startLine-1))
                .Take(lineCount);
Run Code Online (Sandbox Code Playgroud)