I came across an implementation of reading a file line by line that looks like this:
using (StreamReader reader = File.OpenText(path))
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
}
However personally I would do just this:
foreach (string line in File.ReadLines(path))
{
}
Is there any reason to pick one over the other?
Objectively:
The first one is picking the line one by one and you do the process as you stream the data.
The second one generates IEnumerable<string> at once and then you can
start processing the lines (Source MSDN - my apologize to mix it
with ReadAllLines at first).
Usefulness?:
yield in the while loop) till you want to come back at willIEnumerable<string> (that is, to specify the info of the expected data before process) thus giving slightly overhead at first. It is to be noted, however, that this overhead is relatively small as IEnumerable defer the actual execution, unlike List. Some good info to read.And from MSDN The following are the use cases for ReadLines:
Perform LINQ to Objects queries on a file to obtain a filtered set of its lines.
Write the returned collection of lines to a file with the File.WriteAllLines(String, IEnumerable<String>) method, or append them to an existing file with the
File.AppendAllLines(String, IEnumerable<String>) method. Create an immediately populated instance of a collection that takes an IEnumerable<T> collection of strings for its constructor, such as a IList<T> or a Queue<T>.
Is more verbose than method 2. So more chance of things being stuffed up.
Is more concise and encapsulates the intent more directly - much easier to read and follow also less chance of stuffing things up (like forgetting to dispose of the reader etc).
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