C# 从一行到一行读取txt文件到列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16164923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read txt file from line to line to list?
提问by oczxn
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.
需要一些函数来返回带有 txt 文件行的列表(例如,从 10 行到 25 行)。任何解决方案?我所有的尝试都以失败告终。
采纳答案by Alex
// 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);
回答by Sergey Berezovskiy
You can use LINQ and File.ReadLineswhich enumerates over file lines (internally it uses StreamReader):
您可以使用 LINQ 和File.ReadLines枚举文件行(内部使用StreamReader):
List<string> lines = File.ReadLines(path).ToList();
回答by Darren
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);
}
}
回答by user2306455
Check This Out . .. http://www.aspdotnet-suresh.com/2010/12/how-to-read-and-write-text-file-using.html
看一下这个 。.. http://www.aspdotnet-suresh.com/2010/12/how-to-read-and-write-text-file-using.html
Using Stream Else Or strong Builder
使用 Stream Else 或强大的构建器
回答by Machiaweliczny
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
}
回答by Sarrus
If your file isn't too large you can do it with linq:
如果您的文件不是太大,您可以使用 linq 来完成:
int start = 10;
int end = 25;
List<string> lines = File.ReadLines(path).Skip(start - 1).Take(end - start + 1).ToList();

