Read CSV file from and to specific line numbers (e.g. 2 to 50)

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Read CSV file from and to specific line numbers (e.g. 2 to 50)



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#?




3 Answers
3



You can use ReadLines method with LINQ:


ReadLines


File.ReadLines(inputFile).Skip(2).Take(48);



Try this :


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



modified answer based on all comments





I don't think C# works like that :)
– John
Aug 13 at 9:00





What is the issue in the code?
– saravanakumar v
Aug 13 at 9:01





@vasily.sib Because IEnumerable<string> isn't assignable to string last time I checked. File.ReadLines(filename) returns IEnumerable<string>, 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.
– John
Aug 13 at 9:06



IEnumerable<string>


string


File.ReadLines(filename)


IEnumerable<string>


.Skip(2)


.Take(50)





Besides, it is wrong also because it takes 50 lines after the first two not till the 50th line
– Steve
Aug 13 at 9:09





@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 at 9:12



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()





ReadLines in Selman's answer is better since it doesn't have to read the entire file into memory.
– John
Aug 13 at 8:59


ReadLines





ahh fair point!
– Milney
Aug 13 at 9:00





@John: well explained here : stackoverflow.com/questions/21969851/…
– sujith karivelil
Aug 13 at 9:03






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

React Native Navigation and navigating to another Screen problem