Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting the first 10 lines of a file to a string

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?

like image 825
user2891133 Avatar asked Feb 23 '14 09:02

user2891133


People also ask

How to read first 10 lines of a file in c#?

string[] lines = File. ReadLines(path); // reads all lines of the file string[] selectedlines = lines. Take(10); // takes first 10 line s into a new array List<String> LinesList = selectedlines. ToList();

How do you read Top 10 lines in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream.


2 Answers

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.

like image 57
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet


var lines = File.ReadAllLines(path).Take(10);
like image 24
w.b Avatar answered Sep 20 '22 15:09

w.b