Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading specific number of lines from text file in c#

Tags:

c#

c#-4.0

I'm using the following StreamReader to read from text file

string temp = fs.ReadToEnd ();
readlines[i] = temp;   

I want to read a specific number of lines from the text file (let we say, from line number 1 until line number 300 only), then write the lines into one element of array. Could anyone help please? thanks in advance.

like image 570
FSm Avatar asked Jul 04 '12 09:07

FSm


People also ask

How do I read nth line of a file in C using file handling?

You can just use (. ignore) function that you can reiterate using a for loop n times. For example: for (int i = 0 ; i < n ; i++){

How do you read a number from the first line of a file in C?

To read from a text file in C, you will need to open a file stream using the fopen() function. Once a file stream has been opened, you can then read the file line by line using the fgets() function.

How does EOF work in C?

The End of the File (EOF) indicates the end of input. After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.


3 Answers

Use the ReadLine method and add a counter and increase it by line and when you hit 300 do a break out of the loop

like image 146
JohnnBlade Avatar answered Nov 15 '22 15:11

JohnnBlade


Tried with a simple text file.

var lines = File.ReadLines("yourfile").Take(300);
readlines[i] = string.Join("-", lines);
like image 39
Steve Avatar answered Nov 15 '22 15:11

Steve


If you want to skip n first lines and read p lines from there :

var lines = System.IO.File.ReadLines(path).Skip(n).Take(p).ToArray()
like image 24
Kek Avatar answered Nov 15 '22 15:11

Kek