2

I have a .csv file that currently is read all the lines:

 string csv = File.ReadAllText(@inputfile);

suppose there are 100 lines inside that file. I want to read it only from the second line until the 50th lines. how to do that in C#?

DiplomacyNotWar
  • 31,605
  • 6
  • 57
  • 75
Raspi Surya
  • 285
  • 1
  • 10
  • 26

3 Answers3

4

You can use ReadLines method with LINQ:

File.ReadLines(inputFile).Skip(2).Take(48);
Selman Genç
  • 97,365
  • 13
  • 115
  • 182
1

Try this :

var lines = File.ReadLines("inputfile.csv").Skip(1).Take(49);

modified answer based on all comments

Sarav
  • 139
  • 13
  • @John before edit his answer was: `string line = File.ReadLines(@inputfile).Skip(2).Take(50);` which is totally valid. Why do you think that C# didn't works like that? – vasily.sib Aug 13 '18 at 09:06
  • 2
    @vasily.sib Because `IEnumerable` isn't assignable to `string` last time I checked. `File.ReadLines(filename)` returns `IEnumerable`, and by association, so does the `.Skip(2)` and the `.Take(50)`. Also, in case anyone is wondering, I'm not the person who downvoted saravanakumar's answer. – DiplomacyNotWar Aug 13 '18 at 09:06
  • 2
    Besides, it is wrong also because it takes 50 lines after the first two not till the 50th line – Steve Aug 13 '18 at 09:09
  • sorry for the edits and the logical mistake on 50 :| – Sarav Aug 13 '18 at 09:11
  • 1
    @saravanakumarv after all these changes you ended up with an answer that is equal to the first correct one provided. At this point I would consider to delete this one – Steve Aug 13 '18 at 09:12
  • no, as you can see from timestamps, he was the first – vasily.sib Aug 13 '18 at 09:13
  • the first one is logically wrong on skipping 2, taking 48 :P – Sarav Aug 13 '18 at 09:13
  • the question is about reading from second line to 50 .. so skip 1 and take next 49. – Sarav Aug 13 '18 at 09:14
  • @John, saravanakumar v answer is @ 2018-08-13 08:57:5**4**Z, Selman Genç answer @ 2018-08-13 08:57:5**6**Z and Milney answer @ 2018-08-13 08:58:30 – vasily.sib Aug 13 '18 at 09:15
  • @saravanakumar depends how you define 'from' and 'until' as inclusive or exclusive really... – Milney Aug 13 '18 at 12:42
0

You can read all lines, skip the first one and take the remaining 49

List<String> lines = File.ReadAllLines(@inputFile).Skip(1).Take(49).ToList()
Milney
  • 6,067
  • 2
  • 17
  • 30