-6

need some function that will return List with lines of txt file (ex. from 10 line to 25 line). Any solutions? All my tries met with failure.

4

5 回答 5

11

You can use LINQ and File.ReadLines which enumerates over file lines (internally it uses StreamReader):

List<string> lines = File.ReadLines(path).ToList();
于 2013-04-23T08:51:04.580 回答
5

You could do:

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

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
       fileLines.Add(line);
    }
}
于 2013-04-23T08:51:37.513 回答
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);
于 2013-04-23T08:55:04.193 回答
0
List<string> lines = File.ReadLines().ToList();
for(int i = 0; i < lines.Count; i++){
if( i >= startline && i <= endline) LinesFromStartToEnd.Add( lines[i] );// same string list
}
于 2013-04-23T08:56:44.680 回答
0

If your file isn't too large you can do it with linq:

int start = 10;
int end = 25;    
List<string> lines = File.ReadLines(path).Skip(start - 1).Take(end - start + 1).ToList();
于 2013-04-23T09:14:01.943 回答