Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
question from:https://stackoverflow.com/questions/27345854/read-only-first-line-from-a-text-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
96 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can make use of File.ReadLines together with Enumerable.First. This gurantees 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 doesnt read the wole file into an array of lines first.

Edit : Linq also makes sure of properly disposing the FileStream.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...