Read only first line from a text file

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.


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

Tags:

C#