Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read only the first few lines of text from a file

Tags:

c#

How can I read just the first two lines of a file my program saves? (They represent a username and a password.)

like image 569
Oliver Kucharzewski Avatar asked Feb 24 '12 23:02

Oliver Kucharzewski


2 Answers

Use a System.IO.StreamReader.

string line1, line2;

using (StreamReader reader = new StreamReader("myFile.txt")) {
    line1 = reader.ReadLine();
    line2 = reader.ReadLine();
}

Or, for something modern:

var lines = File.ReadLines("myFile.txt").Take(2).ToArray();
like image 56
Ry- Avatar answered Oct 09 '22 19:10

Ry-


For that use StreamReader.ReadLine()

like image 26
Maciej Avatar answered Oct 09 '22 21:10

Maciej