Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenText vs ReadLines

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?

like image 401
Tyress Avatar asked Oct 23 '25 02:10

Tyress


2 Answers

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?:

  • The first one is more "fluid" in that sense. Because you can choose to take/process and break/continue at will. Everytime you need a line, you take one, you process it and then you choose to break or continue. You can even choose to not take any further line (suppose you have yield in the while loop) till you want to come back at will
  • The second one would get IEnumerable<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>.

like image 140
Ian Avatar answered Oct 25 '25 15:10

Ian


Method 1

Is more verbose than method 2. So more chance of things being stuffed up.

Method 2

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

like image 22
Jens Meinecke Avatar answered Oct 25 '25 15:10

Jens Meinecke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!