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; }
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.
ReadAllLines(). First() will actually read all the lines, store them in a string[] and then take the first.
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.
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With