基于线c#读取csv文件 [英] Read csv file based on line c#
问题描述
是可以根据线路读取csv文件。就像给一个行号,并检索CSV特定行。
is it possible to read csv file based on line. Like give a line number and it retrieves that particular line in CSV.
感谢
推荐答案
如果你只是想读取一行一个文本文件(如CSV)的,最简单的方法是使用的 File.ReadLines
和的 Enumerable.ElementAtOrDefault
:
If you just want to read a line of a text file(like csv), the easiest approach is using File.ReadLines
and Enumerable.ElementAtOrDefault
:
public static String getFileLine(String path, int indexOfLine)
{
return File.ReadLines(path).ElementAtOrDefault(indexOfLine);
}
使用它是这样的:
String line = getFileLine(@"C:\Temp\CsvFile.csv", 99);
这将返回100线(或空
。如果有少于100行)
That returns the 100th line (or null
if there are less than 100 lines).
下面是一个返回行范围的另一个类似的方法:
Here's another similar method that returns a range of lines:
public static IEnumerable<String> getFileLines(String path, IEnumerable<int> lineIndices)
{
return File.ReadLines(path).Where((l, i) => lineIndices.Contains(i));
}
返回第10行:
return the first 10 lines:
IEnumerable<int> range = Enumerable.Range(0,10);
IEnumerable<String> lines = getFileLines(@"C:\Temp\CsvFile.csv", range);
foreach (String line in lines)
Console.WriteLine(line);
注意 File.ReadLines
类似于一个的StreamReader
,它不读取整个文件一次到内存中(作为的 FileReadAllLines
),丝毫不亚于必要的。
Note that File.ReadLines
is similar to a StreamReader
, it does not read the whole file at once into memory(as FileReadAllLines
), just as much as necessary.
这篇关于基于线c#读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!