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?
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();
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.
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.
var lines = File.ReadAllLines(path).Take(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With