将文件的前 10 行提取为字符串 [英] Extracting the first 10 lines of a file to a string
问题描述
public void get10FirstLines()
{
StreamReader sr = new StreamReader(path);
String lines = "";
lines = sr.readLine();
}
如何获取字符串中文件的前 10 行?
How can I get the first 10 lines of the file in the string?
推荐答案
与其直接使用 StreamReader
,不如使用 File.ReadLines
返回一个 IEnumerable
Rather than using StreamReader
directly, use File.ReadLines
which returns an IEnumerable<string>
. You can then use LINQ:
var first10Lines = File.ReadLines(path).Take(10).ToList();
使用 File.ReadLines
代替 File.ReadAllLines
是它只读取您感兴趣的行,而不是读取整个文件.另一方面,它仅在 .NET 4+ 中可用.如果您希望在 .NET 3.5 中使用迭代器块,它很容易实现.
The benefit of using File.ReadLines
instead of File.ReadAllLines
is that it only reads the lines you're interested in, instead of reading the whole file. On the other hand, it's only available in .NET 4+. It's easy to implement with an iterator block if you want it for .NET 3.5 though.
对 ToList()
的调用是为了强制对查询进行评估(即实际读取数据),以便恰好读取一次.如果没有 ToList
调用,如果您尝试多次迭代 first10Lines
,它会多次读取文件(假设它完全有效;我似乎记得File.ReadLines
在这方面没有非常干净地实现).
The call to ToList()
is there to force the query to be evaluated (i.e. actually read the data) so that it's read exactly once. Without the ToList
call, if you tried to iterate over first10Lines
more than once, it would read the file more than once (assuming it works at all; I seem to recall that File.ReadLines
isn't implemented terribly cleanly in that respect).
如果您希望前 10 行作为 单个 字符串(例如用\r\n"分隔它们),那么您可以使用 string.Join
:>
If you want the first 10 lines as a single string (e.g. with "\r\n" separating them) then you can use string.Join
:
var first10Lines = string.Join("\r\n", File.ReadLines(path).Take(10));
显然,您可以通过更改调用中的第一个参数来更改分隔符.
Obviously you can change the separator by changing the first argument in the call.
这篇关于将文件的前 10 行提取为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!