public void get10FirstLines()
{
StreamReader sr = new StreamReader(path);
String lines = "";
lines = sr.readLine();
}
How can I get the first 10 lines of the file in the string?
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();
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.
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).
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.