Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read only first line from a text file

Tags:

c#

so what I'm failing to do is, MyFile.txt has either "english", "french" or "german" in the first line and I want to get the language from the first line of the text file, then continue my code

String[] languages = new String[] { "english", "french", "german"};  foreach (String language in languages) {     string line1 = File.ReadLines("MyFile.txt").Skip(0).Take(1);     line1 = language;     continue; } 
like image 235
MiRaN Avatar asked Dec 07 '14 17:12

MiRaN


People also ask

How do I read the first line of a text file?

Open a file using open(filename, mode) as a file with mode “r” and call readline() function on that file object to get the first line of the file.

How do I read the first line of a text file in C#?

ReadAllLines(). First() will actually read all the lines, store them in a string[] and then take the first.

How do you read a specific line in a text file in Python?

Use readlines() to Read the range of line from the File The readlines() method reads all lines from a file and stores it in a list. You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python.


2 Answers

You can make use of File.ReadLines together with Enumerable.First. This guarantees you to only read the first line from the file.

using System.Linq;  

...

string line1 = File.ReadLines("MyFile.txt").First(); // gets the first line from file. 

The difference to File.ReadAllLines is, that File.ReadLines makes use of lazy evaluation and doesn't read the whole file into an array of lines first.

Linq also makes sure of properly disposing the FileStream.

like image 87
CSharpie Avatar answered Sep 21 '22 12:09

CSharpie


To comment on the use of ReadAllLines() in the OP's comment on the answer of CSharpie; it may have a huge impact on the performance if MyFile.txt is a very large file.

File.ReadAllLines().First() will actually read all the lines, store them in a string[] and then take the first. Therefore, if your file is very large, it will store all these lines in the array, which might take some time.

An alternative and better performing option would be to just open a StreamReader and read only the first line. A correct implementation would be;

String[] languages = new String[] { "english", "french", "german"}; string firstLine;  using(StreamReader reader = new StreamReader("MyFile.txt")) {     firstLine = reader.ReadLine() ?? ""; }  if(languages.Contains(firstLine)) {     //... } 

The use of using will take care of closing and disposing the reader. Also, using ?? will make sure null is never returned (and thus saving you an ArgumentNullException on Contains()).

like image 39
Dion V. Avatar answered Sep 21 '22 12:09

Dion V.