Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

c# - Read only first line from a text file

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...